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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
API_DIR="${ROOT_DIR}/dashcaddy-api"
STATUS_DIR="${ROOT_DIR}/status"
PREP_SCRIPT="${ROOT_DIR}/scripts/prepare-release.sh"
OUT_DIR="${1:-${ROOT_DIR}/release}"
CHANNEL="${CHANNEL:-stable}"
BASE_URL="${BASE_URL:-https://get.dashcaddy.net/release}"
CHANGELOG_FILE="${CHANGELOG_FILE:-}"

log() { echo "[publish-release] $*"; }
fail() { echo "[publish-release] ERROR: $*" >&2; exit 1; }

[[ -x "$PREP_SCRIPT" ]] || fail "Missing prepare script: $PREP_SCRIPT"
[[ -f "${API_DIR}/package.json" ]] || fail "Missing API package.json"

VERSION="$(node -pe "require('${API_DIR}/package.json').version")"
COMMIT="$(git -C "${ROOT_DIR}" rev-parse --short HEAD)"
TARBALL_NAME="latest.tar.gz"
VERSION_JSON="version.json"
SHA256_FILE="latest.tar.gz.sha256"

mkdir -p "$OUT_DIR"
rm -f "${OUT_DIR:?}/${TARBALL_NAME}" "${OUT_DIR}/${VERSION_JSON}" "${OUT_DIR}/${SHA256_FILE}"

log "Preparing release inputs..."
"$PREP_SCRIPT"

TMP_DIR="$(mktemp -d)"
cleanup() { rm -rf "$TMP_DIR"; }
trap cleanup EXIT

STAGE_DIR="${TMP_DIR}/dashcaddy"
mkdir -p "$STAGE_DIR"

log "Staging API and dashboard files..."
cp -a "${API_DIR}" "$STAGE_DIR/dashcaddy-api"
cp -a "${STATUS_DIR}" "$STAGE_DIR/status"
cp -a "${ROOT_DIR}/ca" "$STAGE_DIR/ca" 2>/dev/null || true
cp -a "${ROOT_DIR}/dashcaddy-installer" "$STAGE_DIR/dashcaddy-installer" 2>/dev/null || true
cp -a "${ROOT_DIR}/README.md" "$STAGE_DIR/README.md" 2>/dev/null || true

find "$STAGE_DIR" \( -name node_modules -o -name .git -o -name coverage -o -name .nyc_output \) -prune -exec rm -rf {} +
find "$STAGE_DIR" -type f \( -name '*.test.js' -o -name '*.spec.js' \) -delete

log "Creating tarball..."
tar -czf "${OUT_DIR}/${TARBALL_NAME}" -C "$TMP_DIR" dashcaddy
SHA256="$(sha256sum "${OUT_DIR}/${TARBALL_NAME}" | awk '{print $1}')"
printf '%s  %s\n' "$SHA256" "$TARBALL_NAME" > "${OUT_DIR}/${SHA256_FILE}"

CHANGELOG=""
if [[ -n "$CHANGELOG_FILE" && -f "$CHANGELOG_FILE" ]]; then
  CHANGELOG="$(python3 - <<'PY' "$CHANGELOG_FILE"
from pathlib import Path
import json, sys
print(json.dumps(Path(sys.argv[1]).read_text().strip()))
PY
)"
else
  CHANGELOG='"Release published via scripts/publish-release.sh"'
fi

log "Writing version manifest..."
cat > "${OUT_DIR}/${VERSION_JSON}" <<EOF
{
  "version": "${VERSION}",
  "commit": "${COMMIT}",
  "channel": "${CHANNEL}",
  "url": "${BASE_URL}/${TARBALL_NAME}",
  "sha256": "${SHA256}",
  "publishedAt": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
  "changelog": ${CHANGELOG}
}
EOF

log "Release artifacts created in ${OUT_DIR}"
log " - ${TARBALL_NAME}"
log " - ${SHA256_FILE}"
log " - ${VERSION_JSON}"
