#!/bin/sh
# Download this script, then run: sh install-heduian-cli-0.4.23.sh
set -eu
umask 077
heduian_client_version=0.4.23
BASE_URL=https://hda-hk1.oss-cn-hongkong.aliyuncs.com/updates/Linux
if [ "$(uname -s)" != Linux ]; then
    echo '此脚本仅用于 Linux。' >&2
    exit 1
fi
case "$(uname -m)" in
    x86_64|amd64) arch=x86_64; digest=cbf5892a9cf7a7885b209623278a1e06192a4fe7b85da4f8ff5784d2e728170d ;;
    aarch64|arm64) arch=aarch64; digest=6cede4ad435e5912df58040f5d80690bf10f5f037c9f315136f510da8e9787ff ;;
    *) echo '仅支持 x86_64 / ARM64。' >&2; exit 1 ;;
esac
if [ ! -t 0 ]; then
    echo '需要交互式终端输入登录信息。请下载脚本后用 sh 执行。' >&2
    exit 1
fi
# Never run the whole installer with sudo for a normal user's installation.
admin() {
    if [ "$(id -u)" -eq 0 ]; then "$@"; else sudo "$@"; fi
}
# BEGIN distribution detection
ID= VERSION_ID= ID_LIKE=
if [ ! -r /etc/os-release ]; then echo '缺少 /etc/os-release，无法识别系统。' >&2; exit 1; fi
. /etc/os-release
case "$ID" in
    ubuntu|debian|linuxmint|pop|kali) family=deb ;;
    centos|rocky|almalinux|rhel|ol) family=rpm ;;
    *)
        case " ${ID_LIKE:-} " in
            *' debian '*|*' ubuntu '*) family=deb ;;
            *' rhel '*|*' centos '*) family=rpm ;;
            *) echo "暂不支持此发行版：$ID" >&2; exit 1 ;;
        esac ;;
esac
echo "检测到系统：${PRETTY_NAME:-$ID}；架构：$arch"
# END distribution detection
if [ "$family" = deb ]; then
    # Installing binary dependencies does not require refreshing deb-src indexes.
    admin apt-get -o Acquire::IndexTargets::deb-src::Sources::DefaultEnabled=false update
    admin apt-get install -y python3 openssl ca-certificates wget iproute2 libcap2-bin tmux sudo
else
    case "${VERSION_ID%%.*}" in
        7) echo '旧版 EL7 需要可用软件源、Python 3.6+ 及 NetworkManager 1.18+；脚本不会自动替换归档软件源。' ;;
        8|9|10) ;;
        *) echo '当前 RPM 适配目标为 EL7/8/9/10。' >&2; exit 1 ;;
    esac
    if command -v dnf >/dev/null 2>&1; then package_manager=dnf
    elif command -v yum >/dev/null 2>&1; then package_manager=yum
    else echo '缺少 dnf/yum。' >&2; exit 1; fi
    admin "$package_manager" install -y python3 openssl openssl-libs ca-certificates wget iproute libcap tmux sudo NetworkManager policycoreutils
    echo 'DNS 自动选择 systemd-resolved 或已运行的 NetworkManager；不会自动重启网络服务。'
fi
python3 -c 'import sys; sys.exit(0 if sys.version_info >= (3, 6) else "需要 Python 3.6+")'
service_state=$(systemctl is-active heduian-cli.service 2>/dev/null || true)
case "$service_state" in
    active|activating|reloading|deactivating)
        echo '开机连接服务仍在运行或重试，请先执行 heduian stop 再安装。' >&2
        exit 1 ;;
esac
install_home="$HOME/.local/share/heduian-cli"
if [ "$family" = rpm ] && [ "$(id -u)" -eq 0 ]; then install_home=/opt/heduian-cli; fi
mkdir -p "$install_home"
chmod 700 "$install_home"
if ! mkdir "$install_home/install.lock" 2>/dev/null; then
    echo '另一个安装正在进行；如上次被强制中断，请检查后移除安装目录下的 install.lock。' >&2
    exit 1
fi
stage=$(mktemp -d "$install_home/.install.XXXXXX")
cleanup() { rm -rf "$stage"; rmdir "$install_home/install.lock" 2>/dev/null || true; }
trap cleanup EXIT
trap 'exit 130' INT
trap 'exit 143' TERM HUP
archive="heduian-cli-$heduian_client_version-linux-$arch.tar.gz"
echo '正在下载并验证命令行安装包……'
heduian_download_nonce="$(date +%s)-$$"
wget --timeout=30 --tries=3 --header='Cache-Control: no-cache' --header='Pragma: no-cache' \
    -O "$stage/$archive" "$BASE_URL/$archive?heduian_download=$heduian_download_nonce"
python3 - "$stage/$archive" "$digest" "$stage" <<'VERIFY'
import hashlib, sys, tarfile
from pathlib import Path
archive, expected, destination = sys.argv[1:]
path = Path(archive)
actual = hashlib.sha256(path.read_bytes()).hexdigest()
if actual != expected:
    raise SystemExit('安装包 SHA256 不匹配，停止安装。\n预期：' + expected + '\n实际：' + actual +
                     '\n请确认 OSS 安装脚本与安装包属于同一批文件，并清除旧缓存后重试。')
root = path.name[:-7]
with tarfile.open(archive, 'r:gz') as stream:
    for member in stream.getmembers():
        parts = Path(member.name).parts
        if (not parts or parts[0] != root or '..' in parts or
                Path(member.name).is_absolute() or not (member.isfile() or member.isdir())):
            raise SystemExit('安装包包含不安全的归档条目，停止安装。')
    stream.extractall(destination)
print('安装包校验通过。')
VERIFY
# Preserve running installations, including their setcap-enabled core files.
if tmux -L "heduian-auto-$(id -u)" has-session -t heduian-auto 2>/dev/null; then
    echo '已检测到自动后台客户端。请先执行 heduian stop 再重新安装。' >&2
    exit 1
fi
if [ -e "$install_home/current" ] || [ -L "$install_home/current" ]; then
    echo '已有安装将保留；本次安装会切换 current 链接，账号密码不受影响。'
fi
release="$install_home/release-$heduian_client_version-$(date +%Y%m%d%H%M%S)-$$"
mv "$stage/heduian-cli-$heduian_client_version-linux-$arch" "$release"
if [ "$family" = rpm ]; then
    if command -v restorecon >/dev/null 2>&1; then admin restorecon -RF "$install_home"
    elif [ -x /sbin/restorecon ]; then admin /sbin/restorecon -RF "$install_home"; fi
fi
if [ ! -c /dev/net/tun ]; then
    admin modprobe tun || true
fi
(cd "$release" && sh ./enable-tun.sh && ./heduian-cli --mode tun --check)
if [ -e "$install_home/current" ] && [ ! -L "$install_home/current" ]; then
    echo 'current 不是符号链接，停止以避免覆盖目录。' >&2; exit 1
fi
ln -s "$release" "$stage/current"
ln -s current/manager.py "$stage/manager.py"
mv -Tf "$stage/current" "$install_home/current"
mv -Tf "$stage/manager.py" "$install_home/manager.py"
# Refresh an existing managed boot unit so it keeps the same per-user data path.
if [ "$(id -u)" -eq 0 ] && command -v systemctl >/dev/null 2>&1 &&
    systemctl is-enabled --quiet heduian-cli.service 2>/dev/null &&
    grep -q '^# Managed by heduian$' /etc/systemd/system/heduian-cli.service 2>/dev/null; then
    if ! python3 "$install_home/manager.py" autostart on; then
        echo '请执行 heduian autostart on 更新已有开机自启配置。' >&2
    fi
fi
if [ "$(id -u)" -eq 0 ]; then bin_dir=/usr/local/bin; else bin_dir="$HOME/.local/bin"; fi
mkdir -p "$bin_dir"
if [ -e "$bin_dir/heduian" ] || [ -L "$bin_dir/heduian" ]; then
    if [ ! -L "$bin_dir/heduian" ] || [ "$(readlink "$bin_dir/heduian")" != "$install_home/manager.py" ]; then
        echo "已有同名命令，未覆盖。请使用：$install_home/manager.py" >&2
    else
        ln -sfn "$install_home/manager.py" "$bin_dir/heduian"
    fi
else
    ln -s "$install_home/manager.py" "$bin_dir/heduian"
fi
echo '安装完成。即将进入管理菜单：选择 1 登录连接，选择 6 可先设置配置文件地址。'
echo '之后使用 heduian 启动；heduian status 查看；heduian stop 断开；heduian restart 切换节点。'
case ":$PATH:" in *":$bin_dir:"*) ;; *) echo "命令不在 PATH 中时，请使用完整路径：$bin_dir/heduian" ;; esac
echo '首次登录后保存密码；无凭证库时明文存储在用户配置目录，文件权限为 600。'
echo '开机自启默认关闭；连接成功后执行 heduian autostart，在菜单中开启。'
cleanup
trap - EXIT INT TERM HUP
# Keep the real SSH PTY descriptor; opening /dev/tty breaks tmux attach.
exec python3 "$install_home/manager.py"
