#!/bin/sh
#
# Larktun 一键卸载脚本（OpenWrt，opkg/ipk）
#
# 在 OpenWrt 设备上执行：
#   wget -O /tmp/larktun-uninstall.sh https://download.larktun.com/openwrt/uninstall.sh && sh /tmp/larktun-uninstall.sh
#
# 默认会：退出登录(从你的 tailnet 移除本设备) -> 停服务 -> 卸载软件包 -> 清理残留文件与配置/状态。
# 想保留配置与登录状态（仅卸载程序），用：
#   LARKTUN_KEEP_CONFIG=1 sh /tmp/larktun-uninstall.sh
#
set -e

KEEP_CONFIG="${LARKTUN_KEEP_CONFIG:-}"

log() { echo "[INFO]  $*"; }
err() { echo "[ERROR] $*" >&2; }

[ "$(id -u)" = "0" ] || { err "请用 root 运行本脚本。"; exit 1; }

# 1. 退出登录并停掉 tunnel（从 tailnet 注销本设备）
if command -v larktun >/dev/null 2>&1; then
  log "执行 larktun down / logout（从网络注销本设备）..."
  larktun down --accept-risk=lose-ssh 2>/dev/null || true
  larktun logout 2>/dev/null || true
fi

# 2. 停止并禁用服务
if [ -x /etc/init.d/larktun ]; then
  log "停止并禁用 larktun 服务..."
  /etc/init.d/larktun stop 2>/dev/null || true
  /etc/init.d/larktun disable 2>/dev/null || true
fi

# 3. 卸载软件包
if command -v opkg >/dev/null 2>&1 && opkg list-installed 2>/dev/null | grep -q '^larktun '; then
  log "opkg 卸载 larktun..."
  opkg remove larktun 2>/dev/null || true
fi

# 4. 清理可能残留的程序文件（兼容历史/手动安装）
log "清理残留程序文件..."
rm -f /usr/sbin/larktun /usr/sbin/larktund /etc/init.d/larktun /lib/upgrade/keep.d/larktun

# 5. 配置与状态
if [ -n "$KEEP_CONFIG" ]; then
  log "已保留配置与状态：/etc/config/larktun, /etc/larktun/"
else
  log "清理配置与状态..."
  rm -f /etc/config/larktun
  rm -rf /etc/larktun
fi

# 6. 收尾确认
if command -v larktun >/dev/null 2>&1 || [ -f /usr/sbin/larktund ]; then
  err "卸载后仍检测到 larktun 残留，请手动检查 /usr/sbin 与 opkg list-installed。"
  exit 1
fi

log "Larktun 已卸载完成。"
log "提示：依赖 ca-bundle / kmod-tun 未自动移除（可能被其它软件使用）；如确需清理可手动 opkg remove。"
