#!/bin/bash

set -u

PATH="/usr/lib/lwr/setman:$PATH"

source setman-common.sh
source setman-metadata.sh
# for setman_delete_setting
source setman-edit.sh

source setman-list-packages.sh
source setman-list-setting-items.sh

# make the error messages visible for the caller
export SETMAN_LOG_WRITE_TO_STDERR=1
export SETMAN_COMPONENT=setmanctl

subcommand="${1:-}"
shift

setman_execute_action()
{
    local action_with_params=$@
    setman-action write ${action_with_params}
    action_exit_code=$?
    if [[ ${action_exit_code} != 0 ]]; then
        exit ${action_exit_code}
    fi
    action=$(setman-action read)
    setman-log notice "execute action: ${action}"

    systemctl restart setman.target
    setman-action wait
}

show_usage() {
    echo "setmanctl <command>

Commands:
    init
        Check settings integrity, reset, if can't fix (and log)

    default
        Reset settings to factory default values

    backup <backup_path> [--partial|-p <partial_backup_json_string>]
        Store configuration to <backup_path> directory.
        Note: The original content of <backup_path> will be deleted.

        --partial|-p: implies partial backup, preserve only the requested setting groups.
        Example: --partial '{\"preserve\": [\"userConfig\", \"networkConfig\"]}'

    restore <restore_path> [<secondary_restore_path>] [-f|--force]
        Restore configuration from <restore_path> directory.

        If <secondary_restore_path> is given and a setting item is not present
        in <restore_path> then it will be searched in the
        <secondary_restore_path>.

        -f|--force: skip backup metadata checking. It won't check neither
        metadata existence nor metadata version/format/checksums.

    restore-on-boot <restore_path> [<secondary_restore_path>] [-f|--force]
        Same as restore but the execution is deferred until the next boot

    status
        Show action under execution

    wait-service-startup <package-name>
        blocking wait for service startup on boot (init, restore or default) for the given package

    list-package-names
        List packages

    list-packages
        List status of managed service packages

    list-setting-items
        List the info for all active setting items (name, unique, private).
    "
}

process_restore_arguments() {
    local is_forced=$1
    shift
    local backup_paths=$@

    absolute_backup_paths=()
    for backup_path in $backup_paths; do
        verify_restore_output=$(setman_verify_restore $backup_path $is_forced)
        verify_restore_exit_code=$?
        if [ "$verify_restore_exit_code" -ne 0 ]; then
            echo "$verify_restore_output"
            exit $verify_restore_exit_code
        fi
        absolute_backup_paths+=($(realpath "${backup_path}"))
    done

    force_flag=""
    if [[ $is_forced -eq 1 ]]; then
        force_flag=" --force"
    fi

    echo "${absolute_backup_paths[@]}${force_flag}"
}

wait_for_service_startup_finished() {
    package_name=${1}
    signal_file="${SETMAN_SERVICE_STARTUP_FINISHED_PATH}/${package_name}"
    if [[ ! -f "${signal_file}" ]]; then
        echo "Wait for file to exists: ${signal_file}"
        inotifywait -e create --include "${package_name}" "${SETMAN_SERVICE_STARTUP_FINISHED_PATH}"
    else
        echo "Already exists (${signal_file})"
    fi

}

# 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.
positional_args=()
is_forced=0
partial_backup_json=""

while [[ $# -gt 0 ]]; do
    case ${1} in
        -f|--force)
            is_forced=1
            ;;
        -p|--partial)
            shift
            if [[ $# -lt 1 ]]; then
                echo "-p|--partial requires <partial_backup_json>!"
                show_usage
                exit ${SETMAN_ERROR_INVALID_ARGUMENT}
            fi
            partial_backup_json="${1}"
            ;;
        -h|--help)
            show_usage
            exit 0
            ;;
        -*|--*)
            echo "Unknown option: ${1}"
            exit ${SETMAN_ERROR_INVALID_ARGUMENT}
            ;;
        *)
            if [[ -n "${1}" ]]; then
                positional_args+=("${1}")
            fi
    esac
    shift
done

case $subcommand in
    default)
        setman_execute_action default
        ;;
    init)
        setman_execute_action init
        ;;
    status)
        current_action=$(setman-action read)
        echo "current action: ${current_action:-none}"
        ;;
    backup)
        if [[ ${#positional_args[@]} -ne 1 ]]; then
            echo "backup has exactly one argument: <backup-path>"
            exit "${SETMAN_ERROR_INVALID_ARGUMENT}"
        fi

        if [[ -n "${partial_backup_json}" ]]; then
            preserved_setting_items=$(setman_collect_names_by_groups "${partial_backup_json}")
            exit_code=$?
            if [[ ${exit_code} -ne 0 ]]; then
                echo "Error: ${preserved_setting_items}"
                exit ${exit_code}
            fi

            if [[ -z "${preserved_setting_items}" ]]; then
                echo "Error: Partial backup definition yields empty backup"
                exit "${SETMAN_ERROR_INVALID_ARGUMENT}"
            fi
            echo -e "Run partial backup preserving:\n${preserved_setting_items}"
        fi

        backup_path="${positional_args[0]}"
        if [ -d "${backup_path}" ]; then
            setman-log notice "Delete existing backup: ${backup_path}"
        fi
        rm -rf $backup_path
        mkdir -p "${backup_path}/${SETMAN_SETTINGS_DIR_NAME}"

        absolute_backup_path=$(realpath "$backup_path")
        setman_execute_action backup "${absolute_backup_path}"

        if [[ -n "${preserved_setting_items:-}" ]]; then
            # comm: suppress 2: unique to second list
            #       suppress 3: common elements
            setting_items_to_delete=$(comm -23 <(setman_list_setting_items | jq -rM 'keys[]') <(echo -n "${preserved_setting_items}"))
            for item in ${setting_items_to_delete}; do
                setman_delete_setting "${backup_path}" "${item}"
            done
        fi

        ;;
    restore)
        if [[ ${#positional_args[@]} -lt 1 ]]; then
            echo "restore requires at least one restore path!"
            exit ${SETMAN_ERROR_INVALID_ARGUMENT}
        fi

        restore_args_result=$(process_restore_arguments ${is_forced} ${positional_args[@]})
        exit_code=$?
        if [ ${exit_code} -ne 0 ]; then
            echo "${restore_args_result}"
            exit ${exit_code}
        fi

        setman_execute_action restore ${restore_args_result}
        ;;
    restore-on-boot)
        restore_args_result=$(process_restore_arguments ${is_forced} ${positional_args[@]})
        exit_code=$?
        if [ ${exit_code} -ne 0 ]; then
            echo "${restore_args_result}"
            exit ${exit_code}
        fi
        x=$(setman-action write restore ${restore_args_result})
        action_write_exit_code=$?
        if [ ${action_write_exit_code} -ne 0 ]; then
            exit ${action_write_exit_code}
        fi
        exit 0
        ;;
    wait-service-startup)
        if [[ ${#positional_args[@]} -ne 1 ]]; then
            echo "wait-service-startup has exactly one argument: <package-name>"
            exit ${SETMAN_ERROR_INVALID_ARGUMENT}
        fi
        package_name="${positional_args[0]}"
        if $(setmanctl list-package-names | grep -xq "${package_name}"); then
            wait_for_service_startup_finished ${package_name}
        else
            echo "${package_name} not valid package. Valid packages: $(setmanctl list-package-names |  tr '\n' ' ')"
            exit ${SETMAN_ERROR_INVALID_ARGUMENT}
        fi
        ;;
    list-packages)
        setman_list_packages
        ;;
    list-package-names)
        setman_list_active_agents | sed 's/setman-agent@\(.*\)\.service/\1/'
        ;;
    list-setting-items)
        setman_list_setting_items
        ;;
    --help)
        show_usage
        ;;
    *)
        echo "Setmanctl got unknown subcommand: $subcommand"
        show_usage
        exit ${SETMAN_ERROR_INVALID_ARGUMENT}
        ;;
esac
