#!/usr/bin/env bash
# 只安装 Runtime 载荷；调用方必须先停止投递，脚本不管理其他服务。
set -Eeuo pipefail
umask 077
payload=/usr/libexec/agentenv-cri-runtime
state=/var/lib/agentenv-runtime-rpm
server=/usr/local/bin/server
dropin=/etc/systemd/system/aenv.service.d/90-agentenv-runtime.conf
die() { echo "[agentenv-rpm] $*" >&2; exit 1; }
[[ $EUID == 0 ]] || die '需要 root'
action=${1:-status}
shift "$(( $# > 0 ? 1 : 0 ))"
case "$action" in status|activate|deactivate) ;; *) die '用法: agentenv-runtime-package status|activate|deactivate [--drained]' ;; esac
if [[ $action == status ]]; then
    if [[ -f $state/active-version ]]; then cat "$state/active-version"; else echo native; fi
    exit 0
fi
[[ $# == 1 && $1 == --drained ]] || die '请先停止调用方投递并排空 Sandbox，再传入 --drained'
install -d -m 0700 "$state"
exec 9>"$state/lock"
flock -n 9 || die '另一个安装或卸载正在进行'
[[ -x $server ]] || die '未发现原生 AgentENV server'
running=0
if systemctl is-active --quiet aenv.service; then
    running=1
    aenv list --output json | jq -e 'type == "array" and length == 0' >/dev/null || die '存在 Sandbox 或无法确认排空'
fi
# 不终止残留 VM，也不代替调用方进行业务清理。
if pgrep -f '^/var/lib/aenv/deps/firecracker/' >/dev/null; then die '仍有 AgentENV VM 进程'; fi
if [[ $action == activate ]]; then
    (cd "$payload" && sha256sum -c SHA256SUMS >/dev/null) || die '载荷校验失败'
    version=$(jq -er '.patch_version | strings | select(length > 0)' "$payload/manifest.json")
    if [[ -f $state/active-version ]]; then
        cmp -s "$payload/server" "$server" && { echo '当前版本已安装'; exit 0; }
        die '已安装其他版本，请先 deactivate，再安装新版本'
    fi
    [[ ! -e $dropin ]] || die '拒绝覆盖已有同名 drop-in'
    [[ ! -e $state/native-server ]] || die '存在未完成安装的备份，请先检查'
else
    [[ -f $state/active-version ]] || { echo '当前为原生版本'; exit 0; }
    [[ -f $state/native-server ]] || die '原生备份缺失'
    (cd "$state" && sha256sum -c native.sha256 >/dev/null) || die '原生备份损坏'
fi
# 为本次操作保留即时还原点；失败时恢复操作前的二进制和配置。
transaction=$(mktemp -d "$state/transaction.XXXXXX")
cp -p "$server" "$transaction/server"
[[ ! -f $dropin ]] || cp -p "$dropin" "$transaction/dropin"
created_backup=0
rollback() {
    local result=$?
    trap - ERR
    set +e
    local restored=1
    if [[ $running == 1 ]]; then systemctl stop aenv.service || restored=0; fi
    cp -p "$transaction/server" "$server" || restored=0
    if [[ -f $transaction/dropin ]]; then cp -p "$transaction/dropin" "$dropin" || restored=0; else rm -f "$dropin" || restored=0; fi
    systemctl daemon-reload || restored=0
    if [[ $running == 1 ]]; then systemctl start aenv.service || restored=0; fi
    if [[ $restored == 1 && $created_backup == 1 ]]; then
        rm -f "$state/native-server" "$state/native.sha256" "$state/active-version"
    fi
    echo "安装/卸载失败；恢复结果=$restored，还原点保留在 $transaction" >&2
    exit "$result"
}
trap rollback ERR
if [[ $running == 1 ]]; then systemctl stop aenv.service; fi
if [[ $action == activate ]]; then
    cp -p "$server" "$state/native-server"
    created_backup=1
    (cd "$state" && sha256sum native-server > native.sha256)
    install -m 0755 "$payload/server" "$server"
    install -d -m 0755 "${dropin%/*}"
    uid=$(id -u aenv)
    gid=$(id -g aenv)
    printf '[Service]\nRuntimeDirectory=aenv\nEnvironment=AENV_RUNTIME_GRPC_SOCKET=/run/aenv/agentenv-runtime.sock\nEnvironment=AENV_RUNTIME_GRPC_ALLOWED_UIDS=%s,0\nEnvironment=AENV_RUNTIME_GRPC_ALLOWED_GIDS=%s,0\n' "$uid" "$gid" > "$dropin"
    chmod 0644 "$dropin"
else
    cp -p "$state/native-server" "$server"
    rm -f "$dropin"
fi
systemctl daemon-reload
if [[ $running == 1 ]]; then
    systemctl start aenv.service
    ready=0
    for _ in {1..30}; do
        if curl -fsS --max-time 2 http://127.0.0.1:8000/health >/dev/null; then ready=1; break; fi
        sleep 1
    done
    [[ $ready == 1 ]]
fi
if [[ $action == activate ]]; then
    printf '%s\n' "$version" > "$state/active-version"
else
    rm -f "$state/active-version" "$state/native-server" "$state/native.sha256"
fi
trap - ERR
rm -f "$transaction/server" "$transaction/dropin"
rmdir "$transaction"
echo "$action 完成；原有服务启停状态已保留"
