/////
//
// 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
char* perms_to_string(int perms)
{
  char* pstring;
  pstring = malloc(11);
  memcpy(pstring, "----------\0", 11);

  if (perms & 1) pstring[9] = 'x';
  if (perms & 2) pstring[8] = 'w';
  if (perms & 4) pstring[7] = 'r';
  if (perms & 8) pstring[6] = 'x';
  if (perms & 16) pstring[5] = 'w';
  if (perms & 32) pstring[4] = 'r';
  if (perms & 64) pstring[3] = 'x';
  if (perms & 128) pstring[2] = 'w';
  if (perms & 128) pstring[1] = 'r';

  //printf("%s", pstring);

  return pstring;
}

////////////////////////////////////////////////////////////////
// define PAM callback function
int mysql_lookup(char* pattern)//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 like '%s'", pattern); // where url='%s'", r->uri);
   /* send SQL query */
   //if (mysql_query(conn, "show tables")) {
   if (mysql_query(conn, query)) {
      printf("%s\r\n", mysql_error(conn));
      return(-1);
   }
        
   res = mysql_use_result(conn);

   /* output table name */
   printf("ABSEC permissions\r\n");
   int cnt = 0;
   while ((row = mysql_fetch_row(res)) != NULL) {
      printf("%s\t%d\t%d\t%s \r\n", perms_to_string(atoi(row[3])), atoi(row[1]), atoi(row[2]), row[0] );
   }

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

void main(int argc, char** argv)
{
   if (argc>1) {
      mysql_lookup(argv[1]);
   } else {
      mysql_lookup("%");
   }
}