set -euo pipefail
export LC_ALL=C

trap 'rm -rf "$tmpdir"' EXIT
if [[ -z "$TARGET_FILE" || -z "$SRC_URLS" ]]; then
  echo "::error::TARGET_FILE or SRC_URLS is not set"
  exit 1
fi

mkdir -p "$(dirname "$TARGET_FILE")"
tmpdir="$(mktemp -d)"

echo "==> Fetch & normalize from multiple sources"  # 清空聚合临时文件

# 并行抓取并直接流入 awk（-P4 可按带宽/上游限速调整）
: "${FETCH_P:=4}"
printf '%s\n' "$SRC_URLS" \
  | grep -v '^[[:space:]]*$' \
  | xargs -r -P"$FETCH_P" -n1 -I{} sh -c 'echo "  [fetch] {}" >&2; curl -fsSL "{}"' \
  | awk 'BEGIN{IGNORECASE=1}
         {
           # 去掉 no-resolve 及前导空白
           gsub(/,[[:space:]]*no-resolve/,"");
           sub(/^[[:space:]]+/,"");
         }
         /^[[:space:]]*ip-(cidr|asn)/ {
           n=split($0, a, ",");
           pre=toupper(a[1]);
           gsub(/^IP-CIDR6$/, "IP6-CIDR", pre);
           body=a[2]; gsub(/[[:space:]]+/, "", body);
           print pre "," body ",NoMalwares";
         }' \
  | sort -u -T "$tmpdir" > "$tmpdir/remote.norm.list" \
  || { echo "::error::Fetch/normalize pipeline failed"; exit 1; }

count=$(wc -l < "$tmpdir/remote.norm.list")
echo "  => Aggregated sources: ${count} lines after de-dup"

echo "==> Prepare local file (if missing)"
touch "$TARGET_FILE"

echo "==> Build LOCAL compare set (BODY from UPPERCASE lines in CURRENT file)"
awk '/^[[:space:]]*(IP-CIDR|IP6-CIDR|IP-ASN)\b/ {
       n=split($0, a, ",")
       body=a[2]; gsub(/[[:space:]]+/, "", body)
       print body
     }' "$TARGET_FILE" \
  | LC_ALL=C sort -u > "$tmpdir/local.body.list" || true

echo "==> Build REMOTE compare set (BODY)"
awk -F',' '{body=$2; gsub(/[[:space:]]+/, "", body); print body}' "$tmpdir/remote.norm.list" \
  | LC_ALL=C sort -u > "$tmpdir/remote.body.list"

echo "==> Diff on BODY (uppercase-only universe)"
comm -13 "$tmpdir/local.body.list"  "$tmpdir/remote.body.list" > "$tmpdir/to_add.body"    || true
comm -23 "$tmpdir/local.body.list"  "$tmpdir/remote.body.list" > "$tmpdir/to_remove.body" || true

printf "\n\033[1;32m新增的 CIDR/ASN (BODY):\033[0m\n"
[[ -s "$tmpdir/to_add.body" ]] && sed 's/^/  + /' "$tmpdir/to_add.body" || echo "  (无新增)"
printf "\n\033[1;31m移除的 CIDR/ASN (BODY):\033[0m\n"
[[ -s "$tmpdir/to_remove.body" ]] && sed 's/^/  - /' "$tmpdir/to_remove.body" || echo "  (无移除)"

echo "==> Strip previous managed block completely (incl. markers)"
# 删除旧文件中受管区块（包含 begin/end 两行）
sed -e '/^# ===== Managed by GitHub Action: UPPERCASE IP-CIDR \/ IP6-CIDR \/ IP-ASN begin =====$/,/^# ===== Managed by GitHub Action: UPPERCASE IP-CIDR \/ IP6-CIDR \/ IP-ASN end =====$/d' \
    "$TARGET_FILE" > "$tmpdir/local.without_managed"

echo "==> Keep local non-uppercase lines intact"
# 保留小写 ip-cidr/ip-asn 与其它非大写规则
awk '!/^[[:space:]]*(IP-CIDR|IP6-CIDR|IP-ASN)\b/' "$tmpdir/local.without_managed" > "$tmpdir/local.nonupper.keep"

echo "==> Rebuild managed uppercase block to EXACTLY match remote"
cp "$tmpdir/remote.norm.list" "$tmpdir/new.upper.block"

echo "==> Assemble new file"
{
  cat "$tmpdir/local.nonupper.keep"
  printf "# ===== Managed by GitHub Action: UPPERCASE IP-CIDR / IP6-CIDR / IP-ASN begin =====\n"
  cat "$tmpdir/new.upper.block"
  printf "# ===== Managed by GitHub Action: UPPERCASE IP-CIDR / IP6-CIDR / IP-ASN end ====="
} > "$tmpdir/new.NoMalwares.conf"

if ! diff -q "$TARGET_FILE" "$tmpdir/new.NoMalwares.conf" >/dev/null; then
  mv "$tmpdir/new.NoMalwares.conf" "$TARGET_FILE"
  echo "==> Updated NoMalwares.conf"
else
  echo "==> No changes"
fi