#include <mysql.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <sys/stat.h>

int main(int argc, char* argv[]) {
    
// Check if the database name was passed on the cmd-line and if not output usage instructions
// and terminate.
    if(argv[1] == NULL) {
        std::cout << "Usage :\n";
        std::cout << "./docbackup <database_name>\n\n";
        std::cout << "(Where '<database_name>' is the name of the MySQL database to connect to.)\n";
        return 1;
    }
    
    MYSQL *conn;
    MYSQL_RES *res;
    MYSQL_ROW row;

// Usernames and password changed to protect the guilty
// If you need somewhere to start to make this more useful, I'm sure you can
// work out how to pass the server, username and password on the cmd-line rather than
// being evil and hardcoding it. :)
    const char *server = "localhost";
    const char *user = "someuser";
    const char *password = "somepass";
    char *database = argv[1];
    

    std::ofstream myfile;
    std::ofstream logfile;

    conn = mysql_init(NULL);

    // Connect to the database
    if(!mysql_real_connect(conn, server, user, password, database, 0, NULL, 0)) {
        fprintf(stderr, "%s\n", mysql_error(conn));
        return 1;
    }
    
    // Send SQL query
    if(mysql_query(conn, "select uploads.content,uploads.name,LENGTH(uploads.content),clients.legalname,clients.tradingname from uploads LEFT JOIN clients ON uploads.client_id = clients.client_id where 1")) {
        fprintf(stderr, "%s\n", mysql_error(conn));
        return 1;
    }
    
    res = mysql_use_result(conn);
    
    // Create a directory for this database to export files into
    mkdir(argv[1],S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
    std::stringstream f;
    f << argv[1] << "/" << "files.csv";
    std::string logfilename = f.str();
    
    // Output results
    logfile.open(logfilename.c_str(), std::ios::out);
    printf("files:\n");
    while((row = mysql_fetch_row(res)) != NULL) {
        std::string lname;
        std::string tname;
        if(row[3] != NULL)
            lname = row[3];

        if(row[4] != NULL)
            tname = row[4];
            
        std::stringstream s;
        s << "\"" << row[1] << "\"," << "\"" << lname << "\",\"" << tname << "\"" << std::endl;
        std::string log = s.str();
        
        std::stringstream of;
        of << argv[1] << "/" << row[1];
        std::string outfilename = of.str();
        
        myfile.open(outfilename.c_str(), std::ios::binary | std::ios::out );
        int size = strtol(row[2],NULL,0);
        myfile.write(row[0], size);
        myfile.close();
        
        printf("%s (%d)\n", row[1], size);
        
        logfile.write(log.c_str(), log.size());
        
    }
    logfile.close();
        
    // close connection
    mysql_free_result(res);
    mysql_close(conn);
    
    return 1;
}
