#!/bin/bash
# Clash 订阅自动更新脚本
# 直连下载订阅（不走代理，避免循环依赖）→ 注入 required params → 热重载
# Usage: bash update-sub.sh [SUBSCRIPTION_URL]
#
# Customize these variables for your deployment:
#   SUB_URL  — subscription URL (default: reads from ~/clash/sub-url.conf)
#   CONFIG   — path to mihomo config.yaml

set -e

CLASH_DIR="${CLASH_DIR:-$HOME/clash}"

# Read subscription URL from conf file or CLI arg
if [ -n "$1" ]; then
    SUB_URL="$1"
elif [ -f "$CLASH_DIR/sub-url.conf" ]; then
    source "$CLASH_DIR/sub-url.conf"
else
    echo "错误: 找不到 $CLASH_DIR/sub-url.conf，也未传入 URL 参数"
    exit 1
fi

CONFIG="${CONFIG:-$CLASH_DIR/config/config.yaml}"
TMP_FILE=$(mktemp)
LOCK_FILE="/tmp/clash-update.lock"

# 防止并发
exec 200>"$LOCK_FILE"
flock -n 200 || { echo "[$(date -Iseconds)] Already running, skipping"; exit 0; }

echo "[$(date -Iseconds)] Starting subscription update (direct, no proxy)..."

# 直连下载，不走代理
# 原因：代理本身依赖订阅配置，走代理更新 = 循环依赖死锁
HTTP_CODE=$(curl -L --connect-timeout 10 --max-time 30 \
    -H "User-Agent: clash-verge/v2.0.0" \
    -w "%{http_code}" -o "$TMP_FILE" \
    "$SUB_URL" 2>/dev/null)

if [ "$HTTP_CODE" != "200" ]; then
    echo "  FAIL: Subscription download failed (HTTP $HTTP_CODE)"
    rm -f "$TMP_FILE"
    exit 1
fi

# Inject required params that raw subscriptions often omit
sed -i "/external-controller:/c\external-controller: '0.0.0.0:9090'" "$TMP_FILE"
grep -q "^mixed-port:" "$TMP_FILE" || sed -i "1i mixed-port: 7890" "$TMP_FILE"
grep -q "^allow-lan:" "$TMP_FILE" || sed -i "1a allow-lan: true" "$TMP_FILE"
grep -q "^mode:" "$TMP_FILE" || sed -i "1a mode: rule" "$TMP_FILE"
grep -q "^log-level:" "$TMP_FILE" || sed -i "1a log-level: info" "$TMP_FILE"

cp "$TMP_FILE" "$CONFIG"
rm -f "$TMP_FILE"

NODE_COUNT=$(grep -c 'name:' "$CONFIG" 2>/dev/null || echo 0)
echo "  OK: Subscription updated, $NODE_COUNT nodes"

# Hot-reload via mihomo REST API (preferred over restart — preserves connections)
if curl -s -o /dev/null http://127.0.0.1:9090/version 2>/dev/null; then
    curl -s -X PUT http://127.0.0.1:9090/configs \
        -H 'Content-Type: application/json' \
        -d "{\"path\":\"$CONFIG\"}" > /dev/null 2>&1
    echo "  OK: Hot-reload complete"
else
    echo "  WARN: mihomo not running, skipped hot-reload"
fi

echo "[$(date -Iseconds)] Update complete"
