/////
//
// File : absec_ls.c
// Author : Jean-Luc Cyr
// Date : 2018-10
//
// Description: tool to query permissions from mysql database
//

#include <stdio.h>
#include <string.h>
#include <mysql.h>

////////////////////////////////////////////////////////////////
// define PAM callback function
int mysql_update(char *url, int uid, int gid, int perms)
{
   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, "update urls set uid=%d, gid=%d, perms=%d where url='%s'", uid, gid, perms, url); // where url='%s'", r->uri);
   //printf("update urls set uid=%d, gid=%d, perms=%d where url='%s'\r\n", uid, gid, perms, url); // 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);
   }

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

void main(int argc, char** argv)
{
    int perms = 0;
   switch (argc) {
      default:
        printf("Usage: abchmod <perms> <url>\r\n\r\n");
        exit(1);
      break;
      case 2:
        printf("Updating perms on %s\r\n", argv[0]);
        mysql_update(argv[1], 1000, 100, 501);
      break;
      case 3:
        perms = strtol(argv[1], NULL, 8);
        printf("Updating perms on %s to %o (%d)\r\n", argv[2], perms, perms);
        mysql_update(argv[2], 1000, 100, perms);
      break;
   }
}