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

readonly RELEASE_VERSION="20260723-search2"
readonly DEFAULT_BASE_URL="https://botdoc.zhxapp.com/downloads"

BASE_URL="${WXBOT_DOWNLOAD_BASE_URL:-$DEFAULT_BASE_URL}"
DEPLOY_URL="${WXBOT_DEPLOY_URL:-$BASE_URL/wx-bot-linux-deploy.zip?v=$RELEASE_VERSION}"
CHECKSUM_URL="${WXBOT_DEPLOY_CHECKSUM_URL:-$BASE_URL/wx-bot-linux-deploy.zip.sha256?v=$RELEASE_VERSION}"
INSTALL_DIR="${WXBOT_INSTALL_DIR:-$HOME/wx-bot-linux}"

log() {
  printf '[wx-bot] %s\n' "$*"
}

fail() {
  printf '[wx-bot] ERROR: %s\n' "$*" >&2
  exit 1
}

for command_name in curl unzip sha256sum; do
  command -v "$command_name" >/dev/null 2>&1 || fail "缺少 $command_name，请先安装后重试"
done

case "$(uname -m)" in
  x86_64|amd64) ;;
  *) fail "当前只支持 x86_64/amd64 Linux" ;;
esac

tmp_dir="$(mktemp -d)"
trap 'rm -rf "$tmp_dir"' EXIT

archive="$tmp_dir/wx-bot-linux-deploy.zip"
checksum="$tmp_dir/wx-bot-linux-deploy.zip.sha256"

log "下载 Linux 部署包"
curl -fL --retry 3 --connect-timeout 15 -o "$archive" "$DEPLOY_URL"
curl -fL --retry 3 --connect-timeout 15 -o "$checksum" "$CHECKSUM_URL"

expected="$(awk 'NR == 1 {print tolower($1)}' "$checksum")"
actual="$(sha256sum "$archive" | awk '{print tolower($1)}')"
[ -n "$expected" ] && [ "$expected" = "$actual" ] || fail "部署包 SHA-256 校验失败"

unzip -q "$archive" -d "$tmp_dir/unpacked"
source_dir="$tmp_dir/unpacked/wx-bot-linux-deploy"
[ -f "$source_dir/install.sh" ] || fail "部署包缺少 install.sh"

mkdir -p "$INSTALL_DIR"
if [ -d "$INSTALL_DIR/packages" ]; then
  backup_dir="$INSTALL_DIR/backups/$(date +%Y%m%d-%H%M%S)"
  mkdir -p "$backup_dir"
  find "$INSTALL_DIR/packages" -maxdepth 1 -type f -name '*.deb' -exec mv -t "$backup_dir" -- {} + 2>/dev/null || true
fi

cp -a "$source_dir/." "$INSTALL_DIR/"
chmod +x "$INSTALL_DIR/install.sh" "$INSTALL_DIR/bootstrap.sh" "$INSTALL_DIR"/scripts/*.sh

log "部署文件已准备到 $INSTALL_DIR"
cd "$INSTALL_DIR"
exec ./install.sh "$@"
