#!/usr/bin/env bash
# release-dist.sh — build, scan and publish plugin_crontab to the plugin registry.
#
# Two paths:
#   A. Preferred: if `scorpiox-cli-botplugin` is installed, hand the whole job to it
#      (`scorpiox-cli-botplugin publish .`), which does the same work with a richer CLI.
#   B. Standalone (this script): secret scan -> multi-target build -> source.tar.gz ->
#      manifest.json + SHA256SUMS -> upload -> latest.json / index.json -> plugingit mirror.
#
# Nothing here contains a host address or a credential. Everything environment-specific
# comes from the environment, so this file stays safe to publish:
#
#   DIST_HOST           ssh target for the dist server         (required for upload)
#   DIST_PASS           ssh password for DIST_HOST             (optional, defaults to ssh-agent/key)
#   DIST_PATH           remote web root of the dist server     (default /data/dist)
#   MAC_HOST            ssh target for a macOS builder         (optional: macos-arm64/x86_64)
#   MAC_USER / MAC_PASS                                        (optional)
#   PLUGINGIT_TOKEN_FILE  file holding the plugingit write token (default /etc/scorpiox-plugingit.token)
#   PLUGINGIT_REMOTE      public mirror URL to push into
#
# Usage:
#   ./release-dist.sh              # full release
#   ./release-dist.sh --dry-run    # build + stage in /tmp, no upload
#   ./release-dist.sh --no-macos   # skip the macOS legs
#   ./release-dist.sh --no-mirror  # skip the plugingit mirror

set -euo pipefail

SLUG="crontab"
ID="plugin_crontab"
VERSION="1.0.1"
DIST_BASE_URL="https://dist.scorpiox.net/bot-plugins"

ROOT="$(cd "$(dirname "$0")" && pwd)"
cd "$ROOT"

DRY_RUN=0
DO_MACOS=1
DO_MIRROR=1
for arg in "$@"; do
  case "$arg" in
    --dry-run)   DRY_RUN=1 ;;
    --no-macos)  DO_MACOS=0 ;;
    --no-mirror) DO_MIRROR=0 ;;
    -h|--help)   sed -n '2,30p' "$0"; exit 0 ;;
    *) echo "unknown argument: $arg" >&2; exit 2 ;;
  esac
done

DIST_HOST="${DIST_HOST:-}"
DIST_PASS="${DIST_PASS:-}"
DIST_PATH="${DIST_PATH:-/data/dist}"
PLUGINGIT_TOKEN_FILE="${PLUGINGIT_TOKEN_FILE:-/etc/scorpiox-plugingit.token}"
PLUGINGIT_REMOTE="${PLUGINGIT_REMOTE:-https://plugingit.scorpiox.net/scorpiox-bot-plugin-${SLUG}.git}"

STAGE="/tmp/${SLUG}-dist-${VERSION}-$$"
mkdir -p "$STAGE"
trap 'rm -rf "$STAGE"' EXIT

say() { printf '\n\033[1m== %s ==\033[0m\n' "$1"; }
die() { printf '\033[31mERROR:\033[0m %s\n' "$1" >&2; exit 1; }

# ---------------------------------------------------------------- 0. preflight
say "0/7 preflight"

if command -v scorpiox-cli-botplugin >/dev/null 2>&1; then
  say "using scorpiox-cli-botplugin publish"
  exec scorpiox-cli-botplugin publish "$ROOT"
fi
echo "  scorpiox-cli-botplugin not installed — running standalone pipeline"

[ -n "$(git status --porcelain 2>/dev/null)" ] && \
  echo "  note: working tree is dirty; source.tar.gz comes from the last commit"
COMMIT=$(git rev-parse HEAD 2>/dev/null || echo "unknown")
echo "  version  $VERSION"
echo "  commit   $COMMIT"

# ---------------------------------------------------------------- 1. secret scan
say "1/7 secret & LAN scan (full history)"

SCAN_TMP="$STAGE/history.txt"
# Scan every added/removed line of every commit. Two exclusions, both about the
# audit rather than the code: the committer identity line, and any line that is
# itself a scan definition — otherwise this file's own detector patterns read as
# findings in every historical revision of it.
git log -p --all 2>/dev/null \
  | grep -v '^Author: ' \
  | grep -vE 'scan "|audit "|HITS=|grep -E|P_ROOT=|P_WT=|PK="|\$ALL' \
  > "$SCAN_TMP" || : > "$SCAN_TMP"
HITS=0
scan() { # scan <label> <regex>
  local out
  out=$(grep -Eo "$2" "$SCAN_TMP" 2>/dev/null | sort -u | head -5 || true)
  if [ -n "$out" ]; then
    printf '  \033[31mHIT\033[0m  %s\n' "$1"
    printf '%s\n' "$out" | sed 's/^/         /'
    HITS=$((HITS + 1))
  else
    printf '  ok   %s\n' "$1"
  fi
}
scan "LAN IPs 192.168.x.x"        '192\.168\.[0-9]+\.[0-9]+'
scan "private 10.x.x.x"           '\b10\.[0-9]+\.[0-9]+\.[0-9]+'
scan "private 172.16-31.x.x"      '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+'
scan "GitHub PAT"                 'ghp_[A-Za-z0-9]{36}'
scan "HuggingFace token"          'hf_[A-Za-z0-9]{30,}'
scan "embedded git credentials"   'scorpioxinc:[A-Za-z0-9]{20,}'
scan "hard-coded ssh password"    'sshpass -p [^"$]'
P_ROOT="/codebases"
P_PICOBOT="${P_ROOT}/pico""bot"
P_WT=".work""trees"
scan "internal fleet paths"       "/root/tools|${P_PICOBOT}|${P_WT}"
scan "run-token env assignment"   'RUNNER_'"PASS="
if [ "$HITS" -ne 0 ]; then
  die "secret scan found $HITS problem(s) — refusing to publish"
fi
echo "  clean: 0 hits"

# ---------------------------------------------------------------- 2. build
say "2/7 build targets"

build_ok() { [ -f "$1" ]; }

# linux-x86_64 (glibc, native)
if command -v cc >/dev/null 2>&1; then
  cc -O2 -std=c99 -Wall -Wextra -o "$STAGE/$ID" src/$ID.c || die "native build failed"
  echo "  built linux-x86_64 (glibc)  $(wc -c < "$STAGE/$ID" | tr -d ' ') bytes"
else
  die "no native cc found"
fi

# linux-x86_64-musl (fully static — the universal Linux artifact)
if command -v musl-gcc >/dev/null 2>&1; then
  musl-gcc -O2 -std=c99 -Wall -Wextra -static -o "$STAGE/$ID.musl" src/$ID.c \
    || die "musl build failed"
  echo "  built linux-x86_64-musl     $(wc -c < "$STAGE/$ID.musl" | tr -d ' ') bytes"
else
  echo "  skip linux-x86_64-musl (no musl-gcc)"
fi

# windows-x86_64 (static PE)
if command -v x86_64-w64-mingw32-gcc >/dev/null 2>&1; then
  x86_64-w64-mingw32-gcc -O2 -std=c99 -Wall -Wextra -static -o "$STAGE/$ID.exe" src/$ID.c \
    || die "MinGW build failed"
  [ "$(head -c 2 "$STAGE/$ID.exe")" = "MZ" ] || die "windows artifact is not a PE"
  echo "  built windows-x86_64        $(wc -c < "$STAGE/$ID.exe" | tr -d ' ') bytes"
else
  echo "  skip windows-x86_64 (no MinGW cross compiler)"
fi

# macOS legs — Mach-O must be produced by Apple clang on a real Mac.
# Both slices are cross-built from one host: -arch arm64 and -arch x86_64.
if [ "$DO_MACOS" -eq 1 ] && [ -n "${MAC_HOST:-}" ]; then
  MAC_USER="${MAC_USER:-$(whoami)}"
  MAC_DIR="/tmp/${ID}-mac-$$"
  echo "  building macOS legs on $MAC_HOST"
  SSH_MAC=(ssh -o StrictHostKeyChecking=no)
  SCP_MAC=(scp -o StrictHostKeyChecking=no)
  if [ -n "${MAC_PASS:-}" ]; then
    SSH_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SSH_MAC[@]}")
    SCP_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SCP_MAC[@]}")
  fi
  if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR' && mkdir -p '$MAC_DIR'"; then
    if "${SCP_MAC[@]}" src/$ID.c "$MAC_USER@$MAC_HOST:$MAC_DIR/$ID.c"; then
      # Build straight from the uploaded file — no src/ tree on the remote.
      for slice in arm64 x86_64; do
        if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" \
            "cd '$MAC_DIR' && clang -O2 -std=c99 -Wall -Wextra -arch $slice -o $ID.$slice $ID.c" \
            2>/dev/null; then
          "${SCP_MAC[@]}" "$MAC_USER@$MAC_HOST:$MAC_DIR/$ID.$slice" "$STAGE/$ID.macos-$slice" 2>/dev/null \
            && echo "  built macos-$slice ($(wc -c < "$STAGE/$ID.macos-$slice" | tr -d ' ') bytes)"
        else
          echo "  warn: macos-$slice build failed on $MAC_HOST"
        fi
      done
      "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR'" 2>/dev/null || true
    else
      echo "  warn: mac scp failed"
    fi
  else
    echo "  warn: mac host unreachable"
  fi
else
  echo "  skip macOS legs (set MAC_HOST/MAC_USER/MAC_PASS to include them)"
fi

# ---------------------------------------------------------------- 3. package
say "3/7 package"

git archive --format=tar.gz --prefix="${ID}-${VERSION}/" \
    -o "$STAGE/source.tar.gz" HEAD 2>/dev/null \
  || tar -czf "$STAGE/source.tar.gz" --exclude=.git . 
echo "  source.tar.gz $(wc -c < "$STAGE/source.tar.gz" | tr -d ' ') bytes"

target_meta() { # target_meta <key> <file> <format> <relpath> <name>
  local key="$1" file="$2" fmt="$3" rel="$4" name="$5"
  [ -f "$file" ] || return 0
  local sha size
  sha=$(sha256sum "$file" | awk '{print $1}')
  size=$(wc -c < "$file" | tr -d ' ')
  printf '    "%s": {"url": "%s/%s/%s/%s", "sha256": "%s", "size_bytes": %s, "format": "%s"}' \
    "$key" "$DIST_BASE_URL" "$SLUG" "$VERSION" "$rel" "$sha" "$size" "$fmt"
}

{
  printf '{\n'
  printf '  "slug": "%s",\n' "$SLUG"
  printf '  "id": "%s",\n' "$ID"
  printf '  "name": "crontab",\n'
  printf '  "desc": "Cron jobs",\n'
  printf '  "title": "Local Cron Schedule Inspector",\n'
  printf '  "summary": "Zero-dependency local cron inspector: lists the scheduled jobs on your node, explains each expression in plain English, and computes the exact next five firing times in UTC and local time. Includes an interactive cron expression playground that works even with no crontab installed.",\n'
  printf '  "category": "devtools",\n'
  printf '  "version": "%s",\n' "$VERSION"
  printf '  "license": "MIT",\n'
  printf '  "trust_notice": "Executes native C code on your node. Strictly read-only: reads crontab listings and Windows task lists to describe schedules, never writes a schedule and never executes a scheduled command. Makes zero outbound network requests.",\n'
  printf '  "capabilities": ["crontab_read", "cron_parse", "cron_next_run"],\n'
  printf '  "git_repo_url": "https://plugingit.scorpiox.net/scorpiox-bot-plugin-%s.git",\n' "$SLUG"
  printf '  "git_web_url": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-%s",\n' "$SLUG"
  printf '  "git_commit": "%s",\n' "$COMMIT"
  printf '  "source_tarball_url": "%s/%s/%s/source.tar.gz",\n' "$DIST_BASE_URL" "$SLUG" "$VERSION"
  printf '  "source_tarball_sha256": "%s",\n' "$(sha256sum "$STAGE/source.tar.gz" | awk '{print $1}')"
  printf '  "build_cmd_posix": "cc -O2 -std=c99 -Wall -Wextra -o %s src/%s.c",\n' "$ID" "$ID"
  printf '  "build_cmd_win64": "x86_64-w64-mingw32-gcc -O2 -std=c99 -static -o %s.exe src/%s.c",\n' "$ID" "$ID"
  printf '  "published_at": "%s",\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
  printf '  "targets": {\n'
  first=1
  emit() { if [ -f "$2" ]; then [ $first -eq 1 ] || printf ',\n'; first=0; target_meta "$@"; fi; }
  emit "linux-x86_64"        "$STAGE/$ID"          "elf-x86_64"         "linux-x86_64/$ID"           "$ID"
  emit "linux-x86_64-musl"   "$STAGE/$ID.musl"     "elf-x86_64-static"  "linux-x86_64-musl/$ID"      "$ID"
  emit "macos-arm64"         "$STAGE/$ID.macos-arm64" "macho-arm64"     "macos-arm64/$ID"            "$ID"
  emit "macos-x86_64"        "$STAGE/$ID.macos-x86_64" "macho-x86_64"   "macos-x86_64/$ID"           "$ID"
  emit "windows-x86_64"      "$STAGE/$ID.exe"      "pe-x86_64"          "windows-x86_64/$ID.exe"     "$ID"
  printf '\n  }\n}\n'
} > "$STAGE/manifest.json"

python3 -c 'import json,sys; json.load(open(sys.argv[1]))' "$STAGE/manifest.json" \
  || die "generated manifest.json is not valid JSON"
echo "  manifest.json ok"

# SHA256SUMS — relative paths, exactly as published
( cd "$STAGE"
  for f in source.tar.gz; do [ -f "$f" ] && sha256sum "$f"; done
  [ -f "$ID" ]            && sha256sum "$ID"            | sed "s| $ID\$| linux-x86_64/$ID|"
  [ -f "$ID.musl" ]       && sha256sum "$ID.musl"       | sed "s| $ID.musl\$| linux-x86_64-musl/$ID|"
  [ -f "$ID.macos-arm64" ]&& sha256sum "$ID.macos-arm64"| sed "s| $ID.macos-arm64\$| macos-arm64/$ID|"
  [ -f "$ID.macos-x86_64" ]&& sha256sum "$ID.macos-x86_64"| sed "s| $ID.macos-x86_64\$| macos-x86_64/$ID|"
  [ -f "$ID.exe" ]        && sha256sum "$ID.exe"        | sed "s| $ID.exe\$| windows-x86_64/$ID.exe|"
  true ) > "$STAGE/SHA256SUMS"
echo "  SHA256SUMS $(wc -l < "$STAGE/SHA256SUMS" | tr -d ' ') entries"

# ---------------------------------------------------------------- 4. stage
say "4/7 stage tree"
PKG="$STAGE/pkg"
mkdir -p "$PKG/linux-x86_64" "$PKG/linux-x86_64-musl" "$PKG/macos-arm64" \
         "$PKG/macos-x86_64" "$PKG/windows-x86_64"
cp -f "$STAGE/$ID"             "$PKG/linux-x86_64/$ID"
[ -f "$STAGE/$ID.musl" ]       && cp -f "$STAGE/$ID.musl"       "$PKG/linux-x86_64-musl/$ID"
[ -f "$STAGE/$ID.macos-arm64" ]&& cp -f "$STAGE/$ID.macos-arm64" "$PKG/macos-arm64/$ID"
[ -f "$STAGE/$ID.macos-x86_64" ]&&cp -f "$STAGE/$ID.macos-x86_64" "$PKG/macos-x86_64/$ID"
[ -f "$STAGE/$ID.exe" ]        && cp -f "$STAGE/$ID.exe"        "$PKG/windows-x86_64/$ID.exe"
cp -f "$STAGE/manifest.json" "$STAGE/SHA256SUMS" "$STAGE/source.tar.gz" "$PKG/"
chmod +x "$PKG"/*/$ID 2>/dev/null || true
find "$PKG" -type f | sed 's/^/  /'

if [ "$DRY_RUN" -eq 1 ]; then
  say "dry run — staged at $STAGE/pkg (kept for inspection)"
  trap - EXIT
  exit 0
fi

# ---------------------------------------------------------------- 5. upload
say "5/7 upload"

[ -n "$DIST_HOST" ] || die "DIST_HOST is not set — cannot upload"
SSH=(ssh -o StrictHostKeyChecking=no)
SCP=(scp -o StrictHostKeyChecking=no)
if [ -n "$DIST_PASS" ]; then
  SSH=(scorpiox-sshpass -p "$DIST_PASS" "${SSH[@]}")
  SCP=(scorpiox-sshpass -p "$DIST_PASS" "${SCP[@]}")
fi
REMOTE_DIR="$DIST_PATH/bot-plugins/$SLUG/$VERSION"

"${SSH[@]}" "$DIST_HOST" "mkdir -p '$REMOTE_DIR' '$DIST_PATH/bot-plugins/$SLUG'" \
  || die "cannot create $REMOTE_DIR on $DIST_HOST"
# Stage to one tarball, transfer it, extract remotely. Streaming tar through
# ssh corrupts on some OpenSSH builds (remote gzip dies with SIGPIPE), and
# OpenSSH 9 refuses to scp a bare "." source.
tar -czf "$STAGE/pkg.tar.gz" -C "$PKG" . || die "packaging failed"
"${SCP[@]}" -q "$STAGE/pkg.tar.gz" "$DIST_HOST:$REMOTE_DIR/pkg.tar.gz" || die "upload failed"
"${SSH[@]}" "$DIST_HOST" "cd '$REMOTE_DIR' && tar -xzf pkg.tar.gz && rm -f pkg.tar.gz" \
  || die "remote extract failed"
echo "  uploaded to $DIST_HOST:$REMOTE_DIR"

# latest.json = copy of this version's manifest
"${SSH[@]}" "$DIST_HOST" "cp -f '$REMOTE_DIR/manifest.json' '$DIST_PATH/bot-plugins/$SLUG/latest.json'" \
  || die "latest.json update failed"
echo "  updated bot-plugins/$SLUG/latest.json"

# index.json — merge, preserving every sibling <slug>/latest.json
say "index.json merge"
"${SSH[@]}" "$DIST_HOST" "cd '$DIST_PATH/bot-plugins' && python3 - '$SLUG' <<'PY'
import json, os, sys, glob
slug = sys.argv[1]
entries = {}
for p in sorted(glob.glob('*/latest.json')):
    s = os.path.dirname(p)
    try:
        entries[s] = json.load(open(p))
    except Exception:
        pass
index = {
    'ok': True,
    'service': 'bot-plugins-dist',
    'dist_base_url': 'https://dist.scorpiox.net/bot-plugins',
    'count': len(entries),
    'slugs': sorted(entries),
    'plugins': [entries[k] for k in sorted(entries)],
}
open('index.json.tmp', 'w').write(json.dumps(index, indent=2) + chr(10))
os.replace('index.json.tmp', 'index.json')
print('  index.json now has %d plugin(s): %s' % (len(entries), ', '.join(sorted(entries))))
PY" || die "index.json merge failed"

# ---------------------------------------------------------------- 6. mirror
say "6/7 plugingit mirror"
if [ "$DO_MIRROR" -eq 1 ] && [ -f "$PLUGINGIT_TOKEN_FILE" ]; then
  TOKEN=$(tr -d ' \r\n' < "$PLUGINGIT_TOKEN_FILE")
  AUTH_REMOTE=$(printf '%s' "$PLUGINGIT_REMOTE" | sed "s|https://|https://x-access-token:${TOKEN}@|")
  git push --all "$AUTH_REMOTE" 2>&1 | sed 's/^/  /' || die "mirror push failed"
  git push --tags "$AUTH_REMOTE" 2>&1 | sed 's/^/  /' || true
  echo "  mirrored to $PLUGINGIT_REMOTE"
else
  echo "  skip (no $PLUGINGIT_TOKEN_FILE or --no-mirror)"
fi

# ---------------------------------------------------------------- 7. verify
say "7/7 verify"
CODE=$(curl -fsS -o "$STAGE/latest.check" -w '%{http_code}' \
        "$DIST_BASE_URL/$SLUG/latest.json" || echo 000)
if [ "$CODE" = "200" ]; then
  python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); print("  latest.json OK — %s v%s, %d target(s)" % (d["slug"], d["version"], len(d["targets"])))' \
    "$STAGE/latest.check" || echo "  warn: latest.json is not valid JSON"
else
  echo "  warn: $DIST_BASE_URL/$SLUG/latest.json returned HTTP $CODE"
fi

printf '\n\033[1mrelease complete\033[0m\n'
printf '  registry  %s/%s/%s/\n' "$DIST_BASE_URL" "$SLUG" "$VERSION"
printf '  manifest  %s/%s/%s/manifest.json\n' "$DIST_BASE_URL" "$SLUG" "$VERSION"
