#!/bin/bash
set -u

setman_append_to_path() {
   if [[ ":${PATH}:" != *"${1}"* ]]; then
       export PATH="${PATH:+$PATH:}$1"
   fi
}

setman_append_to_path $(realpath $(dirname $0))

source setman-errors.sh
source setman-common.sh

if [[ -z "${SETMAN_COMPONENT+x}" ]]; then
    export SETMAN_COMPONENT="setman-action"
    export SETMAN_LOG_WRITE_TO_STDERR=1
fi

operation=$1
SETMAN_ACTION_DIR="${SETMAN_ACTION_DIR:-/mnt/storage/permanent}"
SETMAN_LOCKFILE_PATH=${SETMAN_LOCKFILE_PATH:-/tmp/setman.lock}
setman_action_file="${SETMAN_ACTION_DIR}/setman-next-action"

show_usage() {
        echo "setman-action <command>

Commands:
    write <action> [<params>]
         initiates <action>, returns error if another action is already in progress. Valid actions are: init, default, backup and restore. 
        Backup and restore also have a <path> parameter, which is the next word.

    read
        returns the current action and params (in case of restore also the force=false/true param). Returns empty string if nothing in progress.
        This read is only for debug purposes, do not parse its output. 
    
    read-action
        same as above, but extracts action

    read-params
        same as above, but extracts params

    read-restore-dirs
        read backup directory paths, from where restore can read data. Returns error if restore is not in progress

    read-backup-dir
        read backup directory path, where backup can write data. Returns error if backup is not in progress

    delete
        deletes the current action. write and delete must be driven by the same logical flow. Calling delete manually can cause serious problems and might cause data loss and render the system unusable.

    is-active
        returns true if there is an action currently in progress, false otherwise.

    is-forced
        returns true if there is restore action currently in progress with --force, false otherwise.

    wait
        blocking wait for setman action finish
    "
}


is_active() {
    if [ -f ${setman_action_file} ]; then
        return 0
    else
        return 1
    fi
}

with_lock()
{
    (
        flock -x 200
        $@
    ) 200>$SETMAN_LOCKFILE_PATH
}

# Please note that there are similarities in command line argument parsing in setmanctl and setman-action.
# Currently we had no better idea to make them more compact and still readable.
parse_action_cli_arguments()
{
    local action=$1
    shift

    positional_args=()
    force="false"

    while [[ $# -gt 0 ]]; do
        case $1 in
            -f|--force)
                force="true"
                shift
                ;;
            -*|--*)
                setman-log error "Unknown option: $1"
                exit ${SETMAN_ERROR_INVALID_ARGUMENT}
                ;;
            *)
                positional_args+=("$1")
                shift
        esac
    done

    case ${action} in
        backup)
            if [[ ${#positional_args[@]} -ne 1 ]]; then
                setman-log error "Invalid ${action} argument(s): ${positional_args[@]}!"
                exit ${SETMAN_ERROR_INVALID_ARGUMENT}
            fi
            params=$(jq -n --arg path ${positional_args[0]} '$ARGS.named')
            ;;
        restore)
            if [[ ${#positional_args[@]} -lt 1 ]]; then
                setman-log error "Invalid ${action} argument(s): ${positional_args[@]}!"
                exit ${SETMAN_ERROR_INVALID_ARGUMENT}
            fi
            paths=$(printf "%s\n" ${positional_args[@]} | jq -cRs 'split("\n")[:-1]')
            params=$(jq -n --argjson paths "${paths}" --argjson force $force '$ARGS.named')
            ;;
        *)
            if [[ ${#positional_args[@]} -ne 0 ]]; then
                setman-log error "Invalid ${action} argument(s): ${positional_args[@]}!"
                exit ${SETMAN_ERROR_INVALID_ARGUMENT}
            fi
            params="{}"
            ;;
    esac

    echo "${params}"
}

require_operation_in_progress() {
    is_active
    if [ $? -ne 0 ]; then
        exit ${SETMAN_ERROR_OPERATION_NOT_IN_PROGRESS}
    fi
}

require_idle() {
    is_active
    if [ $? -eq 0 ]; then
        setman-log error --notify "Another action is already in progress!"
        exit ${SETMAN_ERROR_OPERATION_ALREADY_IN_PROGRESS}
    fi
}

write_next_action() {
    action=$1
    shift;
    setman_is_valid_action ${action}
    require_idle

    params=$(parse_action_cli_arguments ${action} $@)
    if [[ $? -ne 0 ]]; then
        exit ${SETMAN_ERROR_INVALID_ARGUMENT}
    fi
    jq -n --arg action ${action} --argjson params "$params" '{action: $action, ($action + "Params"): $params}' > ${setman_action_file}
}

read_all() {
    require_operation_in_progress

    action=$(read_next_action)

    echo $(read_next_action) $(read_next_action_params)
}

read_next_action() {
    require_operation_in_progress

    jq -r .action $setman_action_file
}

read_next_action_params() {
    require_operation_in_progress

    action=$(read_next_action)
    params=""
    if [[ ${action} == "backup" ]]; then
        path=$(read_action_param backup path)
        params="${path}"
    elif [[ ${action} == "restore" ]]; then
        paths=$(read_action_param restore 'paths[]')
        force=$(read_action_param restore force "false")
        params="${paths} force=${force}"
    fi
    echo "${params}"
}

#
# Utility function for internal use.
#
# read_action_param <action> <json_path> [<alternative>]
#
# `read_action_param restore myparam` returns the value of a restore parameter called `myparam`
# The third (optional) parameter can be used to read optional fields by providing an alternative default:
# `read_action_param restore force "false"`
#
# Returns error if there is no action in progress, or different than `<action>`
#
read_action_param()
{
    action=$1
    json_path=$2
    alternative=${3:+ // $3}

    next_action=$(read_next_action)
    if [ $? -ne 0 ]; then
        exit 1
    fi
    if [[ "${next_action}" != "${action}" ]]; then
        exit 1
    fi

    jq -r ".${action}Params.${json_path}${alternative}" $setman_action_file
}

delete_next_action() {
    require_operation_in_progress
    rm ${setman_action_file}
}

is_forced() {
    force=$(read_action_param restore force "false")
    if [[ "${force}" == "true" ]]; then
        exit 0
    else
        exit 1
    fi
}

wait_for_action_finished() {
    with_lock is_active
    if [ $? -eq 0 ]; then
        wait_output=$(inotifywait -e delete_self ${setman_action_file} 2>&1)
        wait_errc=$?
        if [ ${wait_errc} -ne 0 ]; then
            # inotifywait can return exit if the file does not exist which is not considered an error, but any
            # other case should be reported
            with_lock is_active
            errc=$?
            if [ ${errc} -eq 0 ]; then # still running
                setman-log error "Failed to wait for action to be finished!"
                setman-log error "${wait_output} (error:${wait_errc})"
                exit ${wait_errc}
            fi
        fi
    fi
}

convert_legacy_backup() {
    action=$1
    if [[ "${action}" == "restore" ]]; then
        mkdir -p "${SETMAN_CONVERTED_BACKUP_PATH}" &>/dev/null || true #nyussz: because of local test cases nyussz
        rm -rf "${SETMAN_CONVERTED_BACKUP_PATH:?}"/*
        "$(dirname $0)"/setman-convert-legacy-backup "${SETMAN_CONVERTED_BACKUP_PATH}"
    fi
}

case $operation in
    write)
        shift
        with_lock write_next_action $@
        exit_code=$?
        if [[ ${exit_code} -ne 0 ]]; then
            exit ${exit_code}
        fi
        convert_legacy_backup $@
        exit ${exit_code}
        ;;
    read)
        # This command is only for informing the users. Output shall not be parsed.
        with_lock read_all
        ;;
    read-action)
        with_lock read_next_action
        ;;
    read-params)
        # This command is only for informing the users. Output shall not be parsed.
        with_lock read_next_action_params
        ;;
    read-backup-dir)
        with_lock read_action_param backup path
        ;;
    read-restore-dirs)
        with_lock read_action_param restore 'paths[]'
        ;;
    delete)
        with_lock delete_next_action
        ;;
    is-active)
        with_lock is_active
        ;;
    is-forced)
        with_lock is_forced
        ;;
    wait)
        wait_for_action_finished
        ;;
    --help|-h)
        show_usage
        ;;
    *)
        setman-log error "Unknown operation: ${operation}"
        show_usage
        exit 1
        ;;

esac
