#!/bin/bash

if [ "$EUID" -ne 0 ]; then
    echo -e "\033[0;33mPlease run this script as root user.\033[0m"
    exit 13 # EACCES
fi

if [ -z "${FSX_SHUTILS+x}" ]; then
    real_shell_path=$(readlink -e $0)
    . "$(dirname "${real_shell_path}")/tools/shpack/utils"
fi

# define FLAGS
DEFINE_string 'work_mode' '' 'shell working mode: [ install | update | uninstall | start | repair | status | switch_backend | resize_pool ]' 'm'
DEFINE_boolean 'version' ${FLAGS_FALSE} 'show version' 'v'
DEFINE_boolean 'verbose' ${FLAGS_FALSE} 'show verbose info' ''
DEFINE_boolean 'help' ${FLAGS_FALSE} 'show this help, use \"${FLAGS_PARENT:-$0} -m <mode> -- --help\" for more detail' 'h'
DEFINE_string 'prefix' '/opt/fsx' 'The target directory for fsx installation'
DEFINE_string 'conf_dir' '/opt/tmp/fsx' 'The target directory for fsx configuration'
DEFINE_string 'work_dir' '/opt/tmp/fsx' 'The target directory for fsx working'
if [ -z "${__flags_common_socket_poller_num_type:-}" ]; then
    DEFINE_integer 'common_socket_poller_num' 0 'fusedaemon/fusemonitor socket poller count; 0 means use default'
fi

FLAGS_HELP="USAGE: ${FLAGS_PARENT:-$0} -m <work_mode> [--log_dir=/path/to/log_dir] [--prefix=/path/to/install_dir] [--conf_dir=/path/to/conf_dir] [--work_dir=/path/to/work_dir] [--minloglevel=<minloglevel>] [-- [flags] args]"

# parse the command-line
FLAGS "$@" || exit $?

# try get running log dir if not set log dir
if [ "x${FLAGS_log_dir}" == "x${__flags_log_dir_default}" ]; then
    if bfutils_running_log_path && [ -n "${__bfutils_return}" ]; then
        FLAGS_log_dir=$__bfutils_return
        bfutils_log DEBUG "Use running fsx log dir: \"${FLAGS_log_dir}\""
    fi
fi

bfutils_log DEBUG Running "'${FLAGS_PARENT:-$0}" "$@'" from "'$(pwd)'"
eval set -- "${FLAGS_ARGV}"; bfutils_exit_if_err

# Dynamic modification during scm compilation
RELEASE_VERSION=1.4.0.1881

report_failed_msg_to_fusemonitor() {
    local _exec_mode=$1
    local _error_code=$2
    local _error_msg=$(bfutils_get_log_last_error_msg)
    _error_msg=$(echo "$_error_msg" | sed 's/,/ /g')
    run_fusetool inner report_fsx_util_exec_msg --exec_mode=${_exec_mode} --error_code=${_error_code} --error_msg="${_error_msg}"
}

fsx_common() {
    bfutils_pool_check_work_mode "${FLAGS_work_mode}" || return $?
    bfutils_defer_clean
    local work_script="${deploy_dir}/tools/shpack/${FLAGS_work_mode}.sh"
    bfutils_log DEBUG sourcing "${work_script}"
    unset flags_error
    . "${work_script}"
    common_errno=$?
    if [ ${common_errno} -eq 0 ] || [ "${flags_error}" == "help requested" ]; then
        # status runs as a frequent health probe; skip its success line to avoid flooding dmesg
        if [ "${FLAGS_work_mode}" != "status" ]; then
            bfutils_log ERROR fsx ${FLAGS_work_mode} has finished successfully
        fi
    else
        report_failed_msg_to_fusemonitor ${FLAGS_work_mode} ${common_errno}
        bfutils_log ERROR fsx ${FLAGS_work_mode} has finished with errno: ${common_errno}
    fi
    return ${common_errno}
}

fsx_version() {
    # Get running paths
    if bfutils_running_log_path && [ -n "${__bfutils_return}" ]; then
        FLAGS_log_dir="${__bfutils_return}"
    fi
    if bfutils_running_bin_path && [ -n "${__bfutils_return}" ]; then
        FLAGS_prefix="${__bfutils_return}"
    fi
    if bfutils_running_conf_path && [ -n "${__bfutils_return}" ]; then
        FLAGS_conf_dir=${__bfutils_return}
    fi
    if bfutils_running_work_path && [ -n "${__bfutils_return}" ]; then
        FLAGS_work_dir=${__bfutils_return}
    fi

    output_version=${RELEASE_VERSION}
    fusemonitor_version=""

    run_fusetool inner get_version --instance fusemonitor
    if [ $? -eq 0 ]; then
        fusemonitor_version=${__bfutils_return}
        bfutils_log INFO "Fusemonitor version: ${fusemonitor_version}, binary version: ${RELEASE_VERSION}"
        output_version=${fusemonitor_version}
    else
        bfutils_log WARN "Failed to get fusemonitor version, will return binary version: ${RELEASE_VERSION}"
    fi

    if [ "${FLAGS_verbose}" == "${FLAGS_TRUE}" ]; then
        # try to get all version info
        all_version="Binary version: ${RELEASE_VERSION}\nFusemonitor version: ${fusemonitor_version}"
        for instance in "${supported_instances[@]}"; do
            run_fusetool inner get_version --instance "${instance}"
            if [ $? -eq 0 ]; then
                bfutils_log INFO "Fusedaemon ${instance} version: ${__bfutils_return}"
                all_version+="\nFusedaemon ${instance} version: ${__bfutils_return}"
            fi
        done
        echo -e "${all_version}"
        return 0
    fi

    echo -e "Version: ${output_version}"
    return 0
}

fsx_unknown() {
    bfutils_log ERROR Unknown working mode: "\"${FLAGS_work_mode}\""
    flags_help
    return 22 # EINVAL
}

fsx_main() {
    local main_errno=0

    if [ ${FLAGS_version} == ${FLAGS_TRUE} ]; then
        fsx_version
        main_errno=$?
    elif [[ "x${FLAGS_work_mode}" =~ ^(x(un)?install|xupdate|xstart|xrepair|xclean|xstop|xumount|xone_access_point|xtool|xvke_umount|xstatus|xswitch_backend|xget_transproto|xlock|xresize_pool)$ ]]; then
        FLAGS_HELP="USAGE: ${FLAGS_PARENT:-$0} -m ${FLAGS_work_mode} [--log_dir=/path/to/log_dir] [--minloglevel=<minloglevel>] [-- [flags] args]"
        export "__flags_$(_flags_underscoreName help)_${__FLAGS_INFO_HELP}"='show this help'
        fsx_common "$@"
        main_errno=$?
    else
        fsx_unknown
        main_errno=$?
    fi

    return ${main_errno}
}

bfutils_init
fsx_main "$@"
bfutils_log_shrink $?
bfutils_exit
