#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
TMP_DIR="$(mktemp -d)"
UPSTREAM_REPO_URL="${UPSTREAM_REPO_URL:-https://github.com/blackmatrix7/ios_rule_script.git}"
UPSTREAM_REF="${UPSTREAM_REF:-master}"
TARGET_DIR="${ROOT_DIR}/upstream"

cleanup() {
  rm -rf "$TMP_DIR"
}
trap cleanup EXIT

echo "[sync] clone upstream: $UPSTREAM_REPO_URL@$UPSTREAM_REF"
git clone --depth=1 --branch "$UPSTREAM_REF" "$UPSTREAM_REPO_URL" "$TMP_DIR/upstream" >/dev/null 2>&1

mkdir -p "$TARGET_DIR/rule"
rm -rf "$TARGET_DIR/rule/Surge"
cp -R "$TMP_DIR/upstream/rule/Surge" "$TARGET_DIR/rule/Surge"

UPSTREAM_COMMIT="$(git -C "$TMP_DIR/upstream" rev-parse HEAD)"
UPSTREAM_DATE="$(git -C "$TMP_DIR/upstream" show -s --date=iso --format=%cd HEAD)"

cat > "$TARGET_DIR/README.md" <<TXT
# Local Upstream Cache

This directory is generated by scripts/sync_surge_full.sh.

- Source: $UPSTREAM_REPO_URL
- Ref: $UPSTREAM_REF
- Commit: $UPSTREAM_COMMIT
- Commit Date: $UPSTREAM_DATE
TXT

echo "[sync] done: commit=$UPSTREAM_COMMIT"
