#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <sys/stat.h>
#include "msql.h"

char *datum(char *);

#define PIC_BLOCK 4096

int pass_head=0;

void head(char *code, char *type) {
if (pass_head == 0)
{
	printf("Server: BRUG_httpd/1.0\n");
	printf("Content-type: %s\n", type);
	printf("\n");
}
pass_head=1;
}

void body(char *bg, char *fg) {
printf("<HTML>\n<BODY BGCOLOR=\"%s\" TEXT=\"%s\" LINK=\"%s\" ALINK=\"%s\" VLINK=\"%s\">\n", bg, fg, fg, fg, fg);
}

void log(char *sta) {
if (!pass_head) {
   head("200","text/html");
   body("BLACK", "WHITE");
   }
printf("<BR>\n<CENTER>\n");
printf("<CENTER><TABLE WIDTH=400 BORDER=2 BGCOLOR=#008080>\n");
printf("<TR><TD>\n<BR><CENTER><FONT COLOR=\"BLACK\">%s</FONT></CENTER><BR>\n</TD></TR>\n</TABLE>\n", sta);
}

/* MAIN */

main(int argc, char **argv) {
int i, j, c, msqlsock, credits, rows, cred, size=0, member=0;
char fn[255], line[PIC_BLOCK+1], *user, val[3][200], vreme[10];
FILE *infile;
m_result *mresult;
m_row mrow;

strcpy(line, getenv("QUERY_STRING"));

/* ------------------------------------------------------------------------- */
/* -  Iseci promenjivu koju je poslao WWW server, i vidi sta smo to dobili - */
/* ------------------------------------------------------------------------- */
val[1][0]=0;
val[2][0]=0;

j=0; c=0;
for(i=0; line[i]!=0; i++) {
   if (strncmp(line+i, "view", 4)==0 && j==0) {
      c=1; i+=5; j=0;
      }
   if (strncmp(line+i, "cost", 4)==0 && j==0) {
      c=2; i+=5; j=0;
      }
   val[c][j++]=line[i];
   if (line[i]=='&') {
      val[c][j-1]=0;
      j=0;
      }
      
   }
val[c][j]=0;

size=atoi(val[2]);

if (val[1][0]==0) {
   log("What are you doing?<BR>\nIt seems that you are playng with this CGI!<BR>\nDo it one more time, and i'll inform administrator!");
   exit(0);
   }

/* ------------------------------------------------------------------------- */
/*-		                Cik pogodi ko sam ja	               	     */
/* ------------------------------------------------------------------------- */
user=getenv("REMOTE_USER");
if (user==NULL) {
   log("Server did not supply REMOTE_USER variable.<BR>It seems that you did not protect your CGI-BIN directory.<BR>");
   exit(0);
   }

/* ------------------------------------------------------------------------- */
/*-             Ovde dodajes PATH do direktorijuma sa slikama                */
/* ------------------------------------------------------------------------- */
strcpy(fn, "../../HTML/PROTECT/");
/* ------------------------------------------------------------------------- */
/*-    A zatim se na taj PATH lepi i ono sto prosledi view promenjiva        */
/* ------------------------------------------------------------------------- */
strcat(fn, val[1]);

/* ------------------------------------------------------------------------- */
/*                     Otvaranje FILE-a ... (read, binary)                   */
/* ------------------------------------------------------------------------- */
if ((infile=fopen(fn, "rb"))==NULL) {
   sprintf(line, "It seems that file '%s' does not exist on our server!", fn);
   log(line);
   exit(0);
   }

/* ------------------------------------------------------------------------- */
/*                      Konektovanje na LOCAL mSQL server                    */
/* ------------------------------------------------------------------------- */

if ((msqlsock=msqlConnect(NULL))<0) {
   log("Can not establish connection to mSQL server.");
   log(msqlErrMsg); 
   exit(0);
   }
if (msqlSelectDB(msqlsock, "MEMBERS")<0) {
   log(msqlErrMsg); 
   exit(0);
   }

/* ------------------------------------------------------------------------- */
/*                    Iz baze proveri da li je ovo MEMBER                    */
/* ------------------------------------------------------------------------- */
strcpy(line, "SELECT member FROM user_data WHERE user='");
strcat(line, user); strcat(line, "'");
if ((rows=msqlQuery(msqlsock, line))<0) {
   log(msqlErrMsg); 
   exit(0);
   }
if (rows>1) {
   log("It seems that there is an error in MEMBERS table.");
   exit(0);
   }
mresult=msqlStoreResult();
if ((mrow=msqlFetchRow(mresult))==NULL) {
   log("Upssss, i really don't know how did you came here. Cant find data about you in USER_DATA table.\n");
   exit(0);
   }
member=atoi(mrow[0]);
msqlFreeResult(mresult);
/* ------------------------------------------------------------------------- */
/*              Iz baze proveri koliki kredit ima taj korisnik               */
/* ------------------------------------------------------------------------- */
strcpy(line, "SELECT credit FROM credits WHERE user='");
strcat(line, user); strcat(line, "'");
if ((rows=msqlQuery(msqlsock, line))<0) {
   log(msqlErrMsg); 
   exit(0);
   }
if (rows>1) {
   log("It seems that there is an error in CREDITS table.");
   exit(0);
   }
mresult=msqlStoreResult();
if ((mrow=msqlFetchRow(mresult))==NULL) {
   log("Your data has been received,<BR>but you have not yet been authorized.<BR>Please, allow us 24 hours to process your data.");
   exit(0);
   }

credits=atoi(mrow[0]);

if ((member!=1) && (member!=3) && (member!=4) && (member!=5) && (member!=6) && (member!=8) && (member!=9) && (member!=atoi("a")) && (member!=atoi("s"))) {
   log("It seems that you are no longer a member!<BR>Please, check this with administrator.");
   exit(0);
   }
   
msqlFreeResult(mresult);

if (size==0) { 
   size=100000;
   }

cred=credits-size;

if (cred<0) {
   sprintf(line, "Sorry, it seems that you<BR>DO NOT HAVE enough CREDITS<BR>to retrieve this picture.<BR>You are alowed to retrieve %d bytes.", credits);
   log(line);
   exit(0);
   }

sprintf(line, "UPDATE credits SET credit=%d, datum='%s' WHERE user='%s'", cred, datum(vreme), user);
if (msqlQuery(msqlsock, line)<0) {
   log(msqlErrMsg); 
   exit(0);
   }
msqlClose(msqlsock);


if ( strstr(val[1], ".mpg") || strstr(val[1], ".mpeg") || strstr(val[1], ".mpe") )
{
	head("200", "video/mpeg");
}

if ( strstr(val[1], ".qt") || strstr(val[1], ".mov") )
{
	head("200", "video/quicktime");
}

if ( strstr(val[1], ".avi") )
{
	head("200", "video/x-msvideo");
}

head("200", "image/jpeg");

while ((c=(int)fread(line, 1, PIC_BLOCK, infile))>0)
   fwrite(line, 1, c, stdout);   

fclose(infile);
}

/* ------------------------------------------------------------------------- */
/* -                            Vreme i datum                               - */
/* ------------------------------------------------------------------------- */
char *datum(char *vreme) {
    struct tm *t;
    time_t scs;
    tzset();
    time(&scs);
    t=localtime(&scs);
    strftime(vreme, 8, "19%y%m%d", t);
    return vreme;
}
