#!/usr/bin/env bash
set -Eeuo pipefail
umask 077

BASE_URL="${FASTSERVER_DOWNLOAD_BASE:-http://106.55.18.70/downloads}"
EXPECTED_SHA256='a11671b5cdfc0679e951e1f40f00dd5dcf93962dc2a752e7ab20943159692d6c'
log() { printf '[FastServer] %s\n' "$*"; }
die() { log "$*" >&2; exit 1; }
[[ ${EUID} -eq 0 ]] || die '请使用 root 执行。'
[[ $(uname -m) == x86_64 ]] || die '仅支持 Linux x86-64。'
for cmd in curl gzip sha256sum systemctl pgrep readlink flock ss awk; do
    command -v "$cmd" >/dev/null || die "缺少依赖：$cmd"
done
exec 9>/run/fastserver-update.lock
flock -n 9 || die '另一个更新任务正在运行。'

pids=(); paths=(); oldargs=(); oldcwd=''
while IFS= read -r pid; do
    path=$(readlink "/proc/$pid/exe" 2>/dev/null || true)
    path=${path% (deleted)}
    [[ -n "$path" ]] || continue
    pids+=("$pid"); paths+=("$path")
done < <(pgrep -x FastServer || true)
target=${FASTSERVER_PATH:-}
if ((${#paths[@]})); then
    [[ -n "$target" ]] || target=${paths[0]}
    for path in "${paths[@]}"; do
        [[ "$path" == "$target" ]] || die '发现不同路径的多个实例；请分别处理，避免误停服务。'
    done
    parent=${pids[0]}
    for pid in "${pids[@]}"; do
        ppid=$(awk '/^PPid:/ {print $2}' "/proc/$pid/status" 2>/dev/null || true)
        internal=0
        for other in "${pids[@]}"; do [[ "$ppid" != "$other" ]] || internal=1; done
        if ((internal == 0)); then parent=$pid; break; fi
    done
    oldcwd=$(readlink "/proc/$parent/cwd" || true)
    while IFS= read -r -d '' arg; do oldargs+=("$arg"); done < "/proc/$parent/cmdline"
fi
target=${target:-/root/FastServer}
[[ "$target" == /* && "$target" != *$'\n'* ]] || die '安装路径必须为绝对路径。'
target_dir=$(dirname "$target")
mkdir -p "$target_dir"
target_dir=$(cd "$target_dir" && pwd -P)
target="$target_dir/$(basename "$target")"
[[ ! -L "$target" ]] || die '检测到程序是符号链接，请指定实际文件路径。'
log "检测到安装位置：$target"

work=$(mktemp -d "$target_dir/.fastserver-update.XXXXXX")
changed=0; success=0; backup=''; service=''; created_unit=0; was_active=0; was_enabled=0
dropin=''; had_dropin=0; had_binary=0
cleanup() {
    rc=$?
    trap - EXIT
    if ((changed && !success)); then
        log '更新未通过检查，正在回退。'
        systemctl stop "$service" >/dev/null 2>&1 || true
        if ((had_binary)); then
            cp -p "$backup/FastServer" "$target.rollback" && mv -f "$target.rollback" "$target"
        else
            rm -f "$target"
        fi
        if ((had_dropin)); then cp -p "$backup/update.conf" "$dropin"; else rm -f "$dropin"; fi
        if ((created_unit)); then rm -f "/etc/systemd/system/$service"; fi
        if ((!was_enabled)); then systemctl disable "$service" >/dev/null 2>&1 || true; fi
        systemctl daemon-reload || true
        if ((was_active)); then
            systemctl start "$service" || true
        elif ((${#oldargs[@]})); then
            (cd "${oldcwd:-$target_dir}" && nohup "${oldargs[@]}" >> "$backup/rollback.log" 2>&1 </dev/null &)
        fi
        log "已尝试恢复旧版本。备份：$backup"
        rc=1
    fi
    rm -f "$work/FastServer" "$work/FastServer.gz"
    rmdir "$work" 2>/dev/null || true
    exit "$rc"
}
trap cleanup EXIT
log '下载程序，支持失败重试和断点续传。'
curl -fL --retry 3 --retry-delay 2 --connect-timeout 10 --max-time 300 \
    --continue-at - "$BASE_URL/FastServer-realip-r5-20261106.gz" -o "$work/FastServer.gz"
gzip -dc "$work/FastServer.gz" > "$work/FastServer"
actual=$(sha256sum "$work/FastServer" | awk '{print $1}')
[[ "$actual" == "$EXPECTED_SHA256" ]] || die '下载文件校验失败，旧程序未停止。'
chmod 755 "$work/FastServer"
log 'SHA256 校验通过。'

service=''
for candidate in FastProxy.service fastserver-managed.service; do
    execinfo=$(systemctl show "$candidate" -p ExecStart 2>/dev/null || true)
    if [[ "$execinfo" == *"$target"* ]]; then service=$candidate; break; fi
done
if [[ -z "$service" ]]; then
    service=fastserver-managed.service
    fragment=$(systemctl show "$service" -p FragmentPath 2>/dev/null || true)
    [[ "$fragment" == 'FragmentPath=' || -z "$fragment" ]] || die '已有不匹配的托管服务，请先检查配置。'
    created_unit=1
fi
systemctl is-active --quiet "$service" && was_active=1 || true
systemctl is-enabled --quiet "$service" 2>/dev/null && was_enabled=1 || true
previous_count=$(ss -lntp | awk '/FastServer/ {n++} END {print n+0}')
backup="$target_dir/.fastserver-backup-$(date +%Y%m%d-%H%M%S)-$$"
mkdir -m 700 "$backup"
if [[ -f "$target" ]]; then cp -p "$target" "$backup/FastServer"; had_binary=1; fi
if [[ -f "$target_dir/Fast_log/mac_code.txt" ]]; then cp -p "$target_dir/Fast_log/mac_code.txt" "$backup/mac_code.txt"; fi
if ((${#oldargs[@]})); then printf '%s\0' "${oldargs[@]}" > "$backup/argv.nul"; fi
dropin="/etc/systemd/system/$service.d/90-fastserver-update.conf"
if [[ -f "$dropin" ]]; then cp -p "$dropin" "$backup/update.conf"; had_dropin=1; fi

quote_unit() {
    local v=$1
    v=${v//\\/\\\\}; v=${v//\"/\\\"}; v=${v//%/%%}; v=${v//\$/\$\$}
    printf '"%s"' "$v"
}
changed=1
log '备份完成，停止旧程序。'
systemctl stop "$service" >/dev/null 2>&1 || true
live=()
while IFS= read -r pid; do
    path=$(readlink "/proc/$pid/exe" 2>/dev/null || true)
    path=${path% (deleted)}
    [[ "$path" != "$target" ]] || live+=("$pid")
done < <(pgrep -x FastServer || true)
if ((${#live[@]})); then
    kill -STOP "${live[@]}" 2>/dev/null || true
    kill -KILL "${live[@]}" 2>/dev/null || true
fi
mv -f "$work/FastServer" "$target"
if ((created_unit)); then
    {
        printf '[Unit]\nDescription=FastServer managed service\nWants=network-online.target\nAfter=network-online.target\n[Service]\nType=simple\nWorkingDirectory='
        unit_workdir=${oldcwd:-$target_dir}
        printf '%s' "${unit_workdir//%/%%}"
        printf '\nExecStart='; quote_unit "$target"
        if ((${#oldargs[@]})); then
            index=0
            for arg in "${oldargs[@]:1}"; do
                index=$((index+1))
                [[ "$index" != 1 || "$arg" != install ]] || continue
                printf ' '; quote_unit "$arg"
            done
        fi
        printf '\n[Install]\nWantedBy=multi-user.target\n'
    } > "/etc/systemd/system/$service"
    chmod 644 "/etc/systemd/system/$service"
fi
mkdir -p "$(dirname "$dropin")"
cat > "$dropin" <<'UNIT'
[Service]
Restart=always
RestartSec=5
KillMode=control-group
TimeoutStopSec=10
LimitNOFILE=1048576
UNIT
systemctl daemon-reload
systemctl start "$service"
log '检查服务启动和监听恢复情况（最长约 45 秒）。'
healthy=0; count=0
for attempt in {1..15}; do
    sleep 3
    count=$(ss -lntp | awk '/FastServer/ {n++} END {print n+0}')
    if systemctl is-active --quiet "$service"; then
        if ((previous_count == 0 || count * 10 >= previous_count * 9)); then healthy=1; break; fi
    fi
done
((healthy)) || die "启动检查未通过：更新前 $previous_count 个 TCP 监听，当前 $count 个。"
systemctl enable "$service" >/dev/null
success=1
log "安装成功，当前 TCP 监听数：$count。"
log "服务：$service；已启用开机启动和异常退出重启。"
log "备份位置：$backup"
log '外部 API：http://106.55.18.70:2002/；本机真实IP代理已启用，请用账号验证业务。'
