/* GAdmin-Rsync - An easy to use GTK+ frontend for the rsync backup client and server.
 * Copyright (C) 2007-2011 Magnus Loef <magnus-swe@telia.com> 
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
*/



#include "../config.h"
#include <gtk/gtk.h>
#include "support.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "widgets.h"
#include "allocate.h"
#include "show_info.h"
#include "commands.h"
#include "cron_functions.h"

/* Minute Hour Day-of-month Month Day-of-week root /path/gadmin-rsync-SCRIPT-NAME.sh 
   35 12 * * 1,2,3,4,5,6,7 root /etc/gadmin-rsync/gadmin-rsync-SCRIPT-NAME.sh */

extern gchar *global_scripts_dir;
extern gchar *global_script_log_dir;


gchar *sanitize_backup_name(gchar *backup_name)
{
    int i = 0;
    gchar *bname;

    bname = g_strdup_printf("%s", backup_name);

    /* Add '-' instead of spaces and things in the filename */
    for(i=0; bname[i]!='\0'; i++)
      if( bname[i]==' '  || bname[i]=='/' || bname[i]=='\r'
      ||  bname[i]=='\n' || bname[i]=='\t' )
        bname[i]='-';

    return bname;
}


gchar *mk_backup_script_path(gchar *backup_name)
{
    gchar *path, *bname;

    bname = sanitize_backup_name(backup_name);

    path = g_strdup_printf("%s/gadmin-rsync-%s.sh", global_scripts_dir, bname);

    if( bname!=NULL )
      g_free(bname);

    return path;
}


gchar *mk_backup_at_shutdown_script_path(gchar *backup_name)
{
    gchar *path, *bname;

    bname = sanitize_backup_name(backup_name);

    path = g_strdup_printf("%s/K01gadmin-rsync-%s.sh", SYSTEM_SHUTDOWN_DIR, bname);

    if( bname!=NULL )
      g_free(bname);

    return path;
}


/* Create a link to the backup script. Remove it first if it exists. */
void add_to_system_shutdown(gchar *backup_name)
{
    gchar *shutdown_path, *backup_script_path, *info, *cmd;

    /* Both paths are sanitized */
    backup_script_path = mk_backup_script_path(backup_name);
    shutdown_path = mk_backup_at_shutdown_script_path(backup_name);

    remove_from_system_shutdown(backup_name);

    cmd = g_strdup_printf("ln -s %s %s", backup_script_path, shutdown_path);
    if( ! run_command(cmd) )
    {
	info = g_strdup_printf(_("Error: Unable to create a symlink to the backup script.\n"));
	show_info(info);
	g_free(info);
    }
    if( cmd!=NULL )
      g_free(cmd);

    if( backup_script_path!=NULL )
      g_free(backup_script_path);
    if( shutdown_path!=NULL )
      g_free(shutdown_path);
}


/* Remove any existing links to this backup script */
void remove_from_system_shutdown(gchar *backup_name)
{
    /* The path has been sanitized */
    gchar *shutdown_path = mk_backup_at_shutdown_script_path(backup_name);

    if( file_exists(shutdown_path) && strlen(shutdown_path) > 10 )
      unlink(shutdown_path);

    if( shutdown_path!=NULL )
      g_free(shutdown_path);
}


gchar *mk_restore_script_path()
{
    /* No need to schedule the script. Using underscores
       to differentiate from the backup scripts. */
    gchar *path = g_strdup_printf("%s/gadmin_rsync_restore_script.sh", global_scripts_dir);

    return path;
}


gchar *mk_log_path(gchar *backup_name)
{
    gchar *path, *bname;

    bname = sanitize_backup_name(backup_name);

    path = g_strdup_printf("%s/gadmin-rsync-%s.log", global_script_log_dir, bname);

    if( bname!=NULL )
      g_free(bname);

    return path;
}


gchar *mk_extended_log_path(gchar *backup_name)
{
    gchar *path, *bname;

    bname = sanitize_backup_name(backup_name);

    path = g_strdup_printf("%s/gadmin-rsync-%s.log.details", global_script_log_dir, bname);

    if( bname!=NULL )
      g_free(bname);

    return path;
}


void schedule_cron(gchar *cron_line, gchar *backup_name)
{
    gchar *cmd, *info, *script_path;

    script_path = mk_backup_script_path(backup_name);

    /* Delete matching cron line */
    del_cron(script_path);

    /* Add this cron line */
    add_cron(cron_line, script_path);

    g_free(script_path);

    /* Send a HUP to crond so it rereads crontab */
    cmd = g_strdup_printf("%s", CROND_REREAD_CMD);
    if( ! run_command(cmd) )
    {
	info = g_strdup_printf(_("Error: The time schedule server \"cron(d)\" does not seem to be running.\n"));
	show_info(info);
	g_free(info);
    }
    if( cmd!=NULL )
      g_free(cmd);
}

void add_cron(gchar *cron_line, gchar *script_path)
{
    FILE *fp;

    /* Append a new cron line */
    if((fp=fopen(CRONTAB_PATH, "a"))==NULL)
    {
        return;
    }
    fputs(cron_line, fp);
    fputs(" ", fp);
    fputs(script_path, fp);
    fputs("\n", fp);
    fclose(fp);
}

void del_cron(gchar *script_path)
{
    FILE *fp;
    long file_size = 0;
    char *line, *new_buffer, *path_buffer;
    int i = 0, found_path = 0;

    /* Read crontab file, get everything but the line with this script_path */
    if((fp=fopen(CRONTAB_PATH, "r"))==NULL)
    {
	printf("Error: Can not open crontab file here:\n%s\n", CRONTAB_PATH);
        return;
    }
    fseek(fp, 0, SEEK_END);
    file_size = ftell(fp);
    rewind(fp);

    line = allocate(file_size+1);
    new_buffer = allocate(file_size+1);
    path_buffer = allocate(file_size+1);

    if( file_size > 1 )
    while(fgets(line, file_size, fp)!=NULL)
    {
	for(i=0; line[i]!='\0'; i++)
	{
	    if( line[i]=='/' )
	    {
		found_path = 1;
		break;
	    }
        }
        if( found_path )
        {
    	    found_path = 0;
    	    snprintf(path_buffer, file_size, "%s", &line[i]);

    	    for(i=0; path_buffer[i]!='\0'; i++)
    	    {
    	        if( path_buffer[i]=='\n' )
    	    	    path_buffer[i]='\0';
    	        if( path_buffer[i]=='\r' )
    	    	    path_buffer[i]='\0';
	    }

	    /* We have found our cron line */
	    if( strcmp(path_buffer, script_path) == 0 )
	    {
		/* printf("Cron line found and skipped:\n%s\n", line); */
		continue;
	    }
	    else
	      strcat(new_buffer, line);
	}
	else
	  strcat(new_buffer, line);
    }
    fclose(fp);
    free(line);
    free(path_buffer);

    /* Write the new cron file */
    if((fp=fopen(CRONTAB_PATH, "w+"))==NULL)
    {
	printf("Error: Can not write crontab file here:\n%s\n", CRONTAB_PATH);
        return;
    }
    fputs(new_buffer, fp);
    fclose(fp);
    free(new_buffer);
}
