/////
//
// File : absec_mysql.c
// Author : Jean-Luc Cyr
// Date : 2018-10
//
// Description: Using mysql database as autorisation method
//


#include "absec_auto.h"

#include <mysql.h>
#include <sys/stat.h>
#include "httpd.h"

////////////////////////////////////////////////////////////////
// mysql based permission lookup
int perms_lookup(request_rec *r, struct stat *fperm) 
{
   MYSQL *conn;
   MYSQL_RES *res;
   MYSQL_ROW row;

   char *server = "localhost";
   char *user = "jlcyr";
   char *password = "password"; /* set me first */
   char *database = "absec";

   conn = mysql_init(NULL);

   /* Connect to database */
   if (!mysql_real_connect(conn, server,
         user, password, database, 0, NULL, 0)) {
      printf("%s\n", mysql_error(conn));
      return(0);
   }

    char query[256];
    sprintf(query, "select * from urls where url='%s'", r->uri);
   /* send SQL query */
   //if (mysql_query(conn, "show tables")) {
   if (mysql_query(conn, query)) {
      printf("%s\n", mysql_error(conn));
      return(-1);
   }
        
   res = mysql_use_result(conn);

   /* output table name */
   printf("MySQL data:\n<br/>");
   int cnt = 0;
   while ((row = mysql_fetch_row(res)) != NULL) {
      printf("%s %d %d %o \n<br/>", row[0], atoi(row[1]), atoi(row[2]), atoi(row[3]));
        fperm->st_uid = atoi(row[1]);
        fperm->st_gid = atoi(row[2]);
        fperm->st_mode = atoi(row[3]);
        cnt = cnt + 1;
   }

   if (cnt==0) {
       sprintf(query, "insert into urls (url, uid, gid, perms) values ('%s', %d, %d, %d)", r->uri, fperm->st_uid, fperm->st_gid, fperm->st_mode);
        if (mysql_query(conn, query)) {
            printf("%s\n", mysql_error(conn));
            return(0);
        }
       printf("Aucune donnee\n<br/>");
   }

   /* close connection */
   mysql_free_result(res);
   mysql_close(conn);
   return(0);
}
