#!/bin/sh
# 5itv OpenWrt/Kwrt 一键安装
# 用法: TOKENS_5ITV="pgnfw_xxx" sh install-openwrt-5itv.sh
#   或: sh install-openwrt-5itv.sh pgnfw_xxx,pgnfw_yyy@0
set -e

TOKENS="${1:-${TOKENS_5ITV:-}}"
if [ -z "$TOKENS" ]; then
  echo "用法: TOKENS_5ITV=\"pgnfw_xxx\" sh $0" >&2
  exit 1
fi

# 修改为你指定的服务器基础路径
RAW_BASE="${RAW_5ITV:-https://file.5itv.cn/sh/knock/cvm}"

echo "[1/4] 下载主脚本 -> /usr/bin/5itv"
if [ -f "$(dirname "$0")/../5itv.sh" ]; then
  cp "$(dirname "$0")/../5itv.sh" /usr/bin/5itv
else
  # 指向你服务器上已重命名的 5itv.sh
  curl -sSL -m 30 "$RAW_BASE/5itv.sh" -o /usr/bin/5itv
fi
chmod +x /usr/bin/5itv

echo "[2/4] 写配置 -> /etc/5itv.conf"
cat > /etc/5itv.conf <<EOF
TOKENS_5ITV="$TOKENS"
EOF
chmod 600 /etc/5itv.conf

echo "[3/4] cron 每 10 分钟兜底"
touch /etc/crontabs/root
sed -i '\#/usr/bin/5itv#d' /etc/crontabs/root
echo "*/10 * * * * /usr/bin/5itv >/tmp/5itv.log 2>&1" >> /etc/crontabs/root
/etc/init.d/cron enable >/dev/null 2>&1 || true
/etc/init.d/cron restart >/dev/null 2>&1 || /etc/init.d/cron start

echo "[4/4] hotplug 网络变化即时触发"
mkdir -p /etc/hotplug.d/iface
cat > /etc/hotplug.d/iface/99-5itv <<'EOF'
#!/bin/sh
[ "$ACTION" = ifup ] || exit 0
case "$INTERFACE" in
  wan*|pppoe*) (sleep 5; /usr/bin/5itv >/tmp/5itv.log 2>&1) & ;;
esac
EOF
chmod +x /etc/hotplug.d/iface/99-5itv

echo "安装完成，立即执行一次:"
/usr/bin/5itv