#include "cgic.h"
#include "wbbs.c"

FILE *fptr1,*fptr2;
char buf1[200];

/*** 用來表明讀過某一篇文章 ***/
void
brc_addlist(fname)
  char *fname;
{
  int ftime, n, i;

  if (!cuser.userlevel)
    return;

  ftime = atoi(&fname[2]);
  if (ftime <= 0)
  {
    return;
  }
  if (brc_num <= 0)
  {
    brc_list[brc_num++] = ftime;
    brc_changed = 1;
    return;
  }
  if ((brc_num == 1) && (ftime < brc_list[0]))
    return;
  for (n = 0; n < brc_num; n++)
  {
    if (ftime == brc_list[n])
    {
      return;
    }
    else if (ftime > brc_list[n])
    {
      if (brc_num < BRC_MAXNUM)
        brc_num++;
      for (i = brc_num - 1; --i >= n; brc_list[i + 1] = brc_list[i]);
      brc_list[n] = ftime;
      brc_changed = 1;
      return;
    }
  }
  if (brc_num < BRC_MAXNUM)
  {
    brc_list[brc_num++] = ftime;
    brc_changed = 1;
  }
}



int cgiMain() {
   char *foo, path1[100], path2[100], oneline[301],buf2[100],genbuf[128];
   char *ptr,backup[100];
   time_t t1;
   char *pt1,*pt2;
   int len1, fd, numposts, i,j;
   signed int numarticle, filecount, fd1;
   int ptmode;
   int readmode; //readmode=0 討論區 readmode=1 mail
   struct fileheader readfile;
   struct stat st;
   boardheader *bp;
   boardheader *getbcache();
   char *bdname;
   int querymode=0;//=0 use number to query, =1 prev =2 next 
   strncpy(currboard, getenv("QUERY_STRING"),IDLEN+IDLEN);
   currboard[IDLEN+IDLEN]=0;
   if(!check_passwd())
      return(0);
   foo = rindex(currboard, '_');
   if (foo)
   {
   	*(foo++) = '\0';
   	numarticle = atoi(foo);
   }
   else
   {
	numarticle=Cookienumout;
        querymode=1;
   }
   if (strstr(currboard,"prev")) 
   {
    querymode=1;
    strcpy(currboard,Cboardout);
    numarticle=numarticle-1;
   }
   else if (strstr(currboard,"next")) 
   {
    querymode=2;
    strcpy(currboard,Cboardout);
    numarticle=numarticle+1;
   }

   if (strrchr(currboard,'/')) //恐怕是hacker
   {
      cgiHeaderContentType("text/html");
      fprintf(cgiOut,"<h1>你是hacker嗎？</h1><p>\n");
      return(0);
   }   
   bdname=currboard;
   /** 檢查是不是讀信件區 **/
   if (!strcmp(currboard,"mail")) readmode=1;
   else readmode=0;
   /*** 檢查討論區權限  **/
   bp = getbcache(bdname);
   if(((!bp)||(!Ben_Perm(bp)))&&(!readmode)){
      cgiHeaderContentType("text/html");
      fprintf(cgiOut,"沒有 %s 這個討論區！<p>\n", bdname);
      return(0);
   }
   if (readmode)
      sprintf(path1,BBSHOME "/home/%s/.DIR", cuser.userid);
   else
     sprintf(path1,BBSHOME "/boards/%s/.DIR", currboard);
   if( stat(path1, &st ) >= 0 )
      numposts = st.st_size / (sizeof( struct fileheader ));
   else
      numposts = 0;

   /**** 讀到最後一篇就回到文章列表 **/
   if (numarticle<=0) numarticle=numposts+numarticle; /* 如果輸入負數 */
   if (numarticle<=0) numarticle=1;
   if(numarticle > numposts)
   {
	numarticle = numposts;
	if (readmode==1) sprintf(oneline, "mlist.cgi");
        else sprintf(oneline, "boards.cgi?%s", bdname);
        cgiHeaderLocation(oneline);
   }
   strcpy(Cboardin,currboard);
   Cookienumin=numarticle;
   if(!check_passwd()) return(0);
   cgiHeaderContentType("text/html");
  /* 這裡還要改一下，因為要考慮是否有權限，以及每個版主可以修改 資料 */
   if (readmode) sprintf(buf2,"%s%s", DEFDIR, MREADDEF);
   else sprintf(buf2, "%s%s", DEFDIR, READPRE);
   if( (fptr2 = fopen(buf2,"r")) == NULL )
   {
     fprintf(cgiOut,"%s檔案開啟錯誤<br>",buf2);
     return 0;
   }
   else
   {
    while(fgets(oneline, 300, fptr2) != NULL)  
    {
      pt1=oneline;
      while (pt2=strstr(pt1,"<!--$"))
      {
         *pt2=0;
         pt2=pt2+5;
         fprintf(cgiOut,"%s", pt1);/* 印出token前面的字串 */
         pt1=strstr(pt2,"-->");
         if (pt1==NULL) 
         {
            fprintf(cgiOut,"格式檔錯誤！同一行內找不到對應的 -->");
            return 0;
         }
         *pt1=0;
         pt1=pt1+3;
         ptmode=atoi(pt2);
         if (ptmode==0) //主要功能
         {
          if(numarticle < 0) numarticle = 0;

          fd1 = open(path1, O_RDONLY);
          lseek(fd1, sizeof(readfile)*(numarticle-1), SEEK_SET);
          read(fd1, &readfile, sizeof(readfile));
          close(fd1);
         if (readmode)
	       sprintf(path2,BBSHOME "/home/%s/%s", cuser.userid, 
           readfile.filename);
         else
           sprintf(path2,BBSHOME "/boards/%s/%s", currboard, 
           readfile.filename);
         if((fptr1 = fopen(path2, "r")) == NULL){
            fprintf(cgiOut, "%s 開檔失敗\n", path1);
         return -1;
         }
	 strcpy(backup,currboard);//莫名其妙的currboard會亂掉
         pfile(fptr1);
         fclose(fptr1);

         if (readmode==0)
         {
	    strcpy(currboard,backup);//所以只好用backup來備份了
            setbfile(genbuf,currboard,"wreadnum");
            logcnt(genbuf);/*計錄閱讀次數*/
            /**** 記錄已經讀過了 **/
            brc_initial(currboard);
            brc_addlist(readfile.filename);   
            brc_update();
         }
         else
         {
	        readfile.filemode |= FILE_READ;
       	    if (substitute_record(path1,&readfile,sizeof(readfile),numarticle)) 
             return -1;
         }
        }
        else // other mode
            SSI(ptmode);
      }
      fprintf(cgiOut,"%s", pt1);
    }
      fclose(fptr2);
   }

   return 0;
}
