#!/usr/bin/env bash
set -u

readonly SCRIPT_URL="https://hellomirrors.ivu.cc/hellomirrors.sh"
readonly REPORT_URL="https://hellomirrors.ivu.cc/report.php"
readonly SCRIPT_VERSION="3.0.7"

report_mode="switch"
failure_reporting="prompt"
read_only_request="no"
restore_request="no"
for argument in "$@"; do
    case "$argument" in
    --restore) report_mode="restore"; restore_request="yes" ;;
    --dry-run | -h | --help | -v | --version) read_only_request="yes" ;;
    --no-report) failure_reporting="no" ;;
    --report-failure) failure_reporting="always" ;;
    esac
done

submit_launcher_report() {
    local failure_code="$1" exit_code="$2" payload response=""
    payload="{\"schema_version\":1,\"event\":\"failure\",\"script_version\":\"${SCRIPT_VERSION}\",\"mode\":\"${report_mode}\",\"system\":\"unknown\",\"system_version\":\"unknown\",\"architecture\":\"unknown\",\"protocol\":\"unknown\",\"region\":\"unknown\",\"network\":\"unknown\",\"failure_stage\":\"launcher\",\"failure_code\":\"${failure_code}\",\"exit_code\":${exit_code},\"rollback_result\":\"not_started\"}"
    if response="$(curl -A "hellomirrors-launcher/${SCRIPT_VERSION}" -LfsS \
        --connect-timeout 2 --max-time 3 -H 'Content-Type: application/json' \
        -H 'Accept: text/plain' --data-binary "$payload" "$REPORT_URL" 2>/dev/null)"; then
        response="${response//$'\r'/}"
        response="${response//$'\n'/}"
        if [[ "$response" =~ ^HR-[0-9]{8}-[A-F0-9]{8}$ ]]; then
            printf '  失败报告已发送: %s\n' "$response"
        else
            printf '  失败报告已发送\n'
        fi
    else
        printf '  失败报告未发送成功，不影响本次退出结果\n'
    fi
}

report_launcher_failure() {
    local failure_code="$1" exit_code="$2" answer=""
    printf '\n  启动失败\n\n'
    printf '  阶段  launcher\n'
    printf '  错误  %s · exit %d\n' "$failure_code" "$exit_code"
    printf '  回滚  not_started\n'
    case "$failure_code" in
    SUDO_UNAVAILABLE)
        printf '  处理  当前用户不是 root，且系统没有 sudo；请先执行 su - 切换到 root 后重试\n'
        ;;
    PRIVILEGE_ESCALATION_FAILED)
        printf '  处理  当前用户未能通过 sudo 获取 root 权限；请检查 sudo 授权，或执行 su - 后重试\n'
        ;;
    esac
    [[ "$failure_reporting" != "no" ]] || return 0
    if [[ "$failure_reporting" == "always" ]]; then
        submit_launcher_report "$failure_code" "$exit_code"
        return 0
    fi
    [[ "${launcher_tty:-no}" == "yes" ]] || return 0
    printf '\n  发送以上失败报告以便短期适配？[y/N] '
    IFS= read -r answer <&3 || answer=""
    case "${answer,,}" in
    y|yes) submit_launcher_report "$failure_code" "$exit_code" ;;
    esac
}

launcher_tmp="$(mktemp -d "${TMPDIR:-/tmp}/hellomirrors-launcher.XXXXXX")" || {
    printf '  无法创建启动临时目录\n' >&2
    exit 1
}
bootstrap_file="${launcher_tmp}/hellomirrors.sh"
runner_file="${launcher_tmp}/runner.sh"
started_file="${launcher_tmp}/started"
trap 'rm -rf -- "$launcher_tmp"' EXIT INT TERM HUP

launcher_tty="no"
if { exec 3</dev/tty; } 2>/dev/null; then
    launcher_tty="yes"
fi

if curl -fsSL "$SCRIPT_URL" -o "$bootstrap_file"; then
    :
else
    download_rc=$?
    (( download_rc > 0 && download_rc <= 255 )) || download_rc=1
    report_launcher_failure "SCRIPT_DOWNLOAD_FAILED" "$download_rc"
    exit "$download_rc"
fi

{
    printf '#!/usr/bin/env bash\n'
    printf 'export HELLOMIRRORS_WEB_LAUNCH=yes\n'
    printf 'export HELLOMIRRORS_LAUNCH_MARKER=%q\n' "$started_file"
    printf 'exec bash %q "$@"\n' "$bootstrap_file"
} >"$runner_file" || {
    report_launcher_failure "SCRIPT_START_FAILED" 1
    exit 1
}

launch_method="direct"
requires_root="yes"
if [[ "$read_only_request" == "yes" && "$restore_request" != "yes" ]]; then
    requires_root="no"
fi
if [[ "$requires_root" == "yes" && "$(id -u 2>/dev/null || printf unknown)" != "0" ]]; then
    if command -v sudo >/dev/null 2>&1; then
        launch_method="sudo"
    else
        report_launcher_failure "SUDO_UNAVAILABLE" 127
        exit 127
    fi
fi

if [[ "$launch_method" == "sudo" ]]; then
    launch_command=(sudo bash "$runner_file" "$@")
else
    launch_command=(bash "$runner_file" "$@")
fi

if [[ "$launcher_tty" == "yes" ]]; then
    "${launch_command[@]}" <&3
    launch_rc=$?
else
    "${launch_command[@]}"
    launch_rc=$?
fi

if (( launch_rc != 0 )) && [[ ! -e "$started_file" ]]; then
    if [[ "$launch_method" == "sudo" ]]; then
        report_launcher_failure "PRIVILEGE_ESCALATION_FAILED" "$launch_rc"
    else
        report_launcher_failure "SCRIPT_START_FAILED" "$launch_rc"
    fi
fi

[[ "$launcher_tty" != "yes" ]] || exec 3<&-

exit "$launch_rc"
