#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <syslog.h>

char* concat(char *s1, char *s2)
{
    char *result = malloc(strlen(s1)+strlen(s2)+1);//+1 for the zero-terminator
    strcpy(result, s1);
    strcat(result, s2);
    return result;
}

int main(int argc, char *argv[]) {
	remove("update.log");
	FILE* log = fopen("update.log", "w");
	fprintf(log, "Try to run: supervisorctl stop pilot-server\n");
        int retCode = system("supervisorctl stop pilot-server");
        if (retCode != 0) {
	 fprintf(log, "There is no 'supervisorctl'. Send pkill to Ascon.Pilot.Daemon\n");
         system("pkill -f \"Ascon.Pilot.Daemon\"");
        }
        if (argc > 1) {
	 fprintf(log, "path = %s\n", argv[1]);
        }
	else {
	 fprintf(log, "Arguments are incorrect.\n");
	 return -1;
	}
        char *scriptPath = "sh \"./updateScript.sh\" ";
        char *updatePath = concat(argv[1], "/Update/");
        char *currentPath = argv[1];
        char *resultCommand = concat(scriptPath, "\"");
        resultCommand = concat(resultCommand, updatePath);
        resultCommand = concat(resultCommand, "\" ");
        resultCommand = concat(resultCommand, "\"");
        resultCommand = concat(resultCommand, currentPath);
        resultCommand = concat(resultCommand, "\"");
	fprintf(log, "final = %s\n", resultCommand);
	fclose(log);
        system(resultCommand);
	log = fopen("update.log", "a+");
        if (retCode == 0) {
	 fprintf(log, "Try to run: supervisorctl start pilot-server\n");
         system("supervisorctl start pilot-server\n");
        } else {
	 fprintf(log, "There is no 'supervisorctl'. Cannot run Ascon.Pilot.Daemon\n");
	}
	fclose(log);
        return 0;
}

