#!/usr/bin/env bash
# release-dist.sh - build, scan and publish plugin_services 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.
#
# 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
#   ./release-dist.sh --standalone # use this script even if the CLI is installed
#                                  # (needed for plugins that link extra Win32 libs,
#                                  #  which the CLI's fixed link line cannot express)

set -euo pipefail

SLUG="services"
ID="plugin_services"
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
STANDALONE=0
for arg in "$@"; do
  case "$arg" in
    --standalone) STANDALONE=1 ;;
    --dry-run)   DRY_RUN=1 ;;
    --no-macos)  DO_MACOS=0 ;;
    --no-mirror) DO_MIRROR=0 ;;
    -h|--help)   sed -n '2,32p' "$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 [ "$STANDALONE" -eq 0 ] && command -v scorpiox-cli-botplugin >/dev/null 2>&1; then
  say "using scorpiox-cli-botplugin publish"
  exec scorpiox-cli-botplugin publish "$ROOT"
fi
echo "  running the 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 (and the
# test suite's identical checks) read as findings in every historical revision of
# them. A real secret on any other line still hits.
git log -p --all 2>/dev/null \
  | grep -v '^Author: ' \
  | grep -vE "scan \"|audit \"|HITS=|grep -E|grep -qE|hits '|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"

# linux-x86_64 (glibc, native)
if command -v cc >/dev/null 2>&1; then
  cc -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings -I src -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 -Wno-overlength-strings -I src -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

# linux-arm64-musl (static aarch64 - Raspberry Pi 5 / ARM64 servers)
if command -v aarch64-linux-gnu-gcc >/dev/null 2>&1; then
  aarch64-linux-gnu-gcc -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings -I src -o "$STAGE/$ID.arm64" src/$ID.c \
    || die "arm64 build failed"
  echo "  built linux-arm64-musl      $(wc -c < "$STAGE/$ID.arm64" | tr -d ' ') bytes"
else
  echo "  skip linux-arm64-musl (no aarch64-linux-gnu-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 -Wno-overlength-strings \
    -I src -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
    tar -czf "$STAGE/src.tgz" src
    if "${SCP_MAC[@]}" "$STAGE/src.tgz" "$MAC_USER@$MAC_HOST:$MAC_DIR/src.tgz" \
       && "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "cd '$MAC_DIR' && tar -xzf src.tgz"; 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 -Wno-overlength-strings -I src -arch $slice -o $ID.$slice src/$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'" || true
    else
      echo "  warn: could not upload source to $MAC_HOST"
    fi
  else
    echo "  warn: cannot reach macOS builder $MAC_HOST"
  fi
else
  echo "  skip macOS legs (no MAC_HOST or --no-macos)"
fi

# ---------------------------------------------------------------- 3. manifest
say "3/7 manifest + checksums"

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>
  local key="$1" file="$2" fmt="$3" rel="$4"
  [ -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": "notes",\n'
  printf '  "desc": "Markdown notes",\n'
  printf '  "title": "Markdown Notes",\n'
  printf '  "summary": "Zero-dependency markdown notes that live on your node: create, edit, rename, search, pin and delete, with a live rendered preview next to the editor. Notes are one <id>.md file each plus index.json inside the plugin directory, every write is staged to a temp file and renamed so a crash never truncates a note, and deleted notes go to a recoverable .trash. Server-side rendering escapes note content first, so a pasted <script> is inert text. No CDN, no network requests, no database.",\n'
  printf '  "category": "utilities",\n'
  printf '  "version": "%s",\n' "$VERSION"
  printf '  "license": "MIT",\n'
  printf '  "trust_notice": "Executes native C code on your node. Reads and writes only inside its own notes directory (plugin dir/.notes, or $NOTES_DIR when set): one markdown file per note, an index.json, and a .trash subdirectory. It opens no network connection of any kind and reads nothing outside that directory.",\n'
  printf '  "capabilities": ["fs_write_plugin_dir"],\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"
  emit "linux-x86_64-musl"   "$STAGE/$ID.musl"         "elf-x86_64-static" "linux-x86_64-musl/$ID"
  emit "linux-arm64-musl"    "$STAGE/$ID.arm64"        "elf-arm64-static"  "linux-arm64-musl/$ID"
  emit "macos-arm64"         "$STAGE/$ID.macos-arm64"  "macho-arm64"       "macos-arm64/$ID"
  emit "macos-x86_64"        "$STAGE/$ID.macos-x86_64" "macho-x86_64"      "macos-x86_64/$ID"
  emit "windows-x86_64"      "$STAGE/$ID.exe"          "pe-x86_64"         "windows-x86_64/$ID.exe"
  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 ($(python3 -c 'import json,sys; print(len(json.load(open(sys.argv[1]))["targets"]))' "$STAGE/manifest.json") targets)"

# 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.arm64" ]      && sha256sum "$ID.arm64"      | sed "s| $ID.arm64\$| linux-arm64-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"
cp "$STAGE/manifest.json" "$STAGE/SHA256SUMS" "$STAGE/source.tar.gz" "$PKG/"
[ -f "$STAGE/$ID" ]             && { mkdir -p "$PKG/linux-x86_64";            cp "$STAGE/$ID" "$PKG/linux-x86_64/$ID"; }
[ -f "$STAGE/$ID.musl" ]        && { mkdir -p "$PKG/linux-x86_64-musl";       cp "$STAGE/$ID.musl" "$PKG/linux-x86_64-musl/$ID"; }
[ -f "$STAGE/$ID.arm64" ]       && { mkdir -p "$PKG/linux-arm64-musl";        cp "$STAGE/$ID.arm64" "$PKG/linux-arm64-musl/$ID"; }
[ -f "$STAGE/$ID.macos-arm64" ] && { mkdir -p "$PKG/macos-arm64";             cp "$STAGE/$ID.macos-arm64" "$PKG/macos-arm64/$ID"; }
[ -f "$STAGE/$ID.macos-x86_64" ]&& { mkdir -p "$PKG/macos-x86_64";            cp "$STAGE/$ID.macos-x86_64" "$PKG/macos-x86_64/$ID"; }
[ -f "$STAGE/$ID.exe" ]         && { mkdir -p "$PKG/windows-x86_64";          cp "$STAGE/$ID.exe" "$PKG/windows-x86_64/$ID.exe"; }
echo "  staged: $(find "$PKG" -type f | wc -l | tr -d ' ') file(s)"

if [ "$DRY_RUN" -eq 1 ]; then
  say "dry run - leaving the staging tree in $PKG"
  trap - EXIT
  exit 0
fi

# ---------------------------------------------------------------- 5. upload
say "5/7 upload to the dist server"
[ -n "$DIST_HOST" ] || die "DIST_HOST is not set (export DIST_HOST=<ssh-target>)"
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://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"
