source "$(dirname "${BASH_SOURCE[0]}")/config.sh";
source "$(dirname "${BASH_SOURCE[0]}")/recommendations.sh";
source "$PROJECT_ROOT/utils.sh";

alert_file_names="csf free_memory ftp imap pop spamd puppet smtp cp_license disk_usage dns_query backup_age cpu_load swap";

for alert in $alert_file_names; do
        alert_file="${alert}.sh";
        source "$(dirname "${BASH_SOURCE[0]}")/${alert_file}";
done;

script_lock_check(){
        local lock_file="$1";
        local timeout_threshold=${2:-172800}; # 48 hours by default

        if [[ ! -e $lock_file ]]; then
                return;
        fi;

        local lock_file_age=$(get_file_age_in_sec "$lock_file");

        if [[ $lock_file_age -gt $timeout_threshold ]]; then
                rm -f $lock_file;
        else
                echo $SCRIPT_SKIP;
        fi;
}

get_file_age_in_sec(){
        local file="$1";

        if [[ ! -e $file ]]; then
               echo 999999999; # Default, very old age, to prevent an infinite lock in some cases
        else
                local b_date="$(stat $file | grep Change: | cut -d' ' -f2-3 | cut -d. -f1)";
                local b_date_seconds="$(date -d"$b_date" +%s)";
                echo $(( $(date +%s) - $b_date_seconds ));
        fi;
}

run_check_in_background(){
        declare -A background_data;
        local background_script=$1;
        local background_data_file="$2";
        local bg_script_errors="${3:-/dev/null}";
        local lock_file="$4";
        background_data[script_status]=$(script_lock_check "$lock_file");

        if [[ -e "$background_data_file" && -n $(grep $SCRIPT_SKIP "$background_data_file") ]]; then
                rm -f "$background_data_file";
        fi;

        if [[ ${background_data[script_status]} =~ "$SCRIPT_SKIP" ]]; then
                bash_arr_to_json background_data ${!background_data[@]} | tee $background_data_file;
                return;
        elif [[ ! -e "$background_data_file" ]]; then
                logdir_check;
                touch "$background_data_file" 2>/dev/null;
                if [[ $? -ne 0 ]]; then
                        background_data[script_status]=$SCRIPT_START_FAIL;
                else
                        start_in_background "$background_script" 2>$bg_script_errors;
                        background_data[script_status]=$SCRIPT_STARTED;
                fi;

        elif [[ $(file "$background_data_file") =~ $EMPTY_FILE ]]; then
                background_data[script_status]=$(progress_or_timeout "$background_data_file");
        else
                cat "$background_data_file";
                rm -f "$background_data_file";

                if [[ -e "$bg_script_errors" && ! $(file "$bg_script_errors") =~ $EMPTY_FILE ]]; then
                        errors=$(cat "$bg_script_errors");
                        write_log "$(awk -F/ '{print $NF}' <<< $bg_script_errors):" "$errors" &>/dev/null;
                fi;

                rm -f "$bg_script_errors";

                return;
        fi;

        bash_arr_to_json background_data ${!background_data[@]}
}

json_escape(){
        sed -z "s/\n/\\\n/g" | sed -z "s/\t/\\\t/g" | sed -z "s/\"/'/g";
}

bash_arr_to_json(){ # args: array name, array keys. returns: json string
        local name=$1[@];
        shift;
        local arr=("${!name}");
        local keys=($@);
        local json_str="{$(for ((i=0; $i < ${#keys[@]}; ((++i)) )); do echo -n "\"${keys[$i]}\":\"${arr["$i"]}\",";
                done)}";
        echo $json_str | sed "s:,\}$:}:";
}

start_in_background(){
        $1 & disown;
}

progress_or_timeout(){
        local data_file="$1";
        local day_in_seconds=86400; # 24 hours
        local data_file_age=$(get_file_age_in_sec "$data_file");

        if [[ $data_file_age -gt $day_in_seconds ]]; then
                rm -f $data_file;
                echo $SCRIPT_TIMEOUT;
        else
                echo $SCRIPT_IN_PROGRESS;
        fi;
}

logdir_check(){
        # Create the background data directory if it doesn't exists
        if [[ ! -e $BACKGROUND_DATA ]]; then
                mkdir -p $BACKGROUND_DATA;
        fi;
}
