// deployer NginxModule implementation
// Copyright (C) 2024 Jean-Cloud
// GNU General Public License v3

#include <filesystem>
#include <fstream>
#include "BashManager.h"
#include "NginxModule.h"
using namespace std;
namespace fs=filesystem;

//constructor
NginxModule::NginxModule(){
    name="Nginx";
}

//destructor inline

//public methods
int NginxModule::Prepare ()
{
    cout << "nginx preparation" << endl;
    //create proxy_dir
    string proxy_dir=getenv("PROXY_DIR");
    fs::create_directories(proxy_dir);

    //delete current new_conf directory (to start from scratch)
    string new_nginx_conf_path=getenv("NEW_NGINX_CONF_PATH");
    fs::remove_all(new_nginx_conf_path);

    //create new new_conf directory
    fs::create_directories(new_nginx_conf_path);

    //create new conf file (for tests purposes)
    string nginx_conf_path=getenv("NGINX_CONF_PATH");
    //open the old conf file
    ifstream input("./services/_proxy/nginx.conf");
    if (!input) {
        std::cerr << "Error when opening /services/_proxy/nginx.conf" << std::endl;
        return 1;
    } else {
        stringstream buffer;
        buffer << input.rdbuf();
        string content = buffer.str();
        input.close();
        //replace nginx_conf_path with the new nginx_conf_path in the conf
        size_t pos=content.find(nginx_conf_path);
        while (pos!=string::npos){
            content.replace(pos,nginx_conf_path.length(),new_nginx_conf_path);
            pos=content.find(nginx_conf_path);
        }
        //fill the new conf file
        ofstream output (proxy_dir+"/new_nginx.conf");
        output << content;
        output.close();
    }
    return 0;
}

int NginxModule::Deploy (string serviceUsername)
{
    //write the new conf 
    //copy the conf from the service directory to the nginx directory
    string conf="./services/"+serviceUsername+"/nginx_server.conf";
    string new_nginx_conf_path=getenv("NEW_NGINX_CONF_PATH");
    //nginx dir
    fs::create_directories(new_nginx_conf_path + "/" + serviceUsername);
    fs::copy(conf,new_nginx_conf_path+"/"+serviceUsername);
    string newConf=new_nginx_conf_path + "/" + serviceUsername + "/nginx_server.conf";
    //replace the environment variables with their values
    string cmd="envsubst < "+ conf + " > " + newConf;
    BashManager::Execute(cmd);

    //test new conf
    //cmd = "nginx -t -c /etc/nginx/new_nginx.conf && echo $?"
    //string res = BashManager
    return 0;
}

int NginxModule::Remove(string serviceUsername)
{
    return 0;
}

int NginxModule::Clean ()
{
    cout << "nginx cleaning" << endl;
    return 0;
}