#!/usr/bin/env bash
# OSSL Agent 卸载脚本（https://get.ossl.cn/uninstall.sh）
#
#   curl -fsSL https://get.ossl.cn/uninstall.sh | bash
#
# 停止并移除 systemd 服务、删除 /opt/ossl（含本机身份）与 /usr/local/bin/ossl。
# 卸载后要在这台机器重新接入：控制台「重置绑定」拿新令牌，再执行安装命令。

set -euo pipefail

INSTALL_DIR="/opt/ossl"
BIN="${INSTALL_DIR}/ossl"
LINK_PATH="/usr/local/bin/ossl"
UNIT_NAME="ossl"

ok()  { printf '\033[1;32m ✔\033[0m %s\n' "$*"; }
die() { printf '\033[1;31m ✘\033[0m %s\n' "$*" >&2; exit 1; }

main() {
  [ "$(id -u)" -eq 0 ] || die "需要 root 权限：curl -fsSL https://get.ossl.cn/uninstall.sh | sudo bash"

  if [ -f "/etc/systemd/system/${UNIT_NAME}.service" ] && command -v systemctl >/dev/null 2>&1; then
    systemctl stop "${UNIT_NAME}" >/dev/null 2>&1 || true
    systemctl disable "${UNIT_NAME}" >/dev/null 2>&1 || true
    rm -f "/etc/systemd/system/${UNIT_NAME}.service"
    systemctl daemon-reload >/dev/null 2>&1 || true
    ok "已移除 systemd 服务 ${UNIT_NAME}"
  fi

  if [ -x "${BIN}" ]; then
    "${BIN}" stop </dev/null >/dev/null 2>&1 || true
  fi

  if [ -L "${LINK_PATH}" ] || [ -f "${LINK_PATH}" ]; then
    rm -f "${LINK_PATH}"
  fi
  if [ -d "${INSTALL_DIR}" ]; then
    rm -rf "${INSTALL_DIR}"
    ok "已删除 ${INSTALL_DIR}"
  fi

  cat <<EOF

OSSL Agent 已卸载。重新接入：控制台「重置绑定」获取新令牌后执行安装命令。
EOF
}

main "$@"
