#!/bin/sh
# Peakstone release uploader. Works in any CI (GitLab, Jenkins, Woodpecker, Forgejo, GitHub...) or on your machine.
#
#   curl -fsSL https://peakstone.app/peakstone.sh | sh -s -- release
#
# Needs two variables, kept in your CI's secret store:
#   PEAKSTONE_TOKEN        an API token with releases:write (Dashboard > API tokens)
#   PEAKSTONE_LISTING_ID   the listing id (shown on the API tokens page)
#
# It finds the jar (build/libs or target), takes the version from the tag (v1.2.3 becomes 1.2.3), picks the beta or
# alpha channel for versions like 1.2.3-beta.1, uploads, and fails the job if Peakstone refuses the release.
# Docs: https://peakstone.app/docs/api#other-ci
set -eu

PEAKSTONE_URL="${PEAKSTONE_URL:-https://peakstone.app}"

usage() {
  cat <<'EOF'
Usage: peakstone.sh release [options]

Options:
  --jar PATH          jar to upload (default: newest jar in build/libs or target)
  --version VERSION   version (default: from the CI tag or `git describe`, without a leading "v")
  --notes TEXT        release notes
  --notes-file PATH   release notes from a file (for example CHANGELOG excerpt)
  --channel NAME      stable, beta or alpha (default: from the version)
  --security-fix      mark the release as a security fix
  --listing ID        listing id (default: $PEAKSTONE_LISTING_ID)
  --dry-run           show what would be uploaded, upload nothing
EOF
}

fail() { echo "peakstone: $*" >&2; exit 1; }

[ "${1:-}" = "release" ] || { usage; [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ] && exit 0; exit 2; }
shift

JAR=""; VERSION=""; NOTES=""; NOTES_FILE=""; CHANNEL=""; SECURITY=""; DRY=""
LISTING="${PEAKSTONE_LISTING_ID:-}"
while [ $# -gt 0 ]; do
  case "$1" in
    --jar) JAR="${2:?--jar needs a path}"; shift 2 ;;
    --version) VERSION="${2:?--version needs a value}"; shift 2 ;;
    --notes) NOTES="${2:?--notes needs text}"; shift 2 ;;
    --notes-file) NOTES_FILE="${2:?--notes-file needs a path}"; shift 2 ;;
    --channel) CHANNEL="${2:?--channel needs stable, beta or alpha}"; shift 2 ;;
    --security-fix) SECURITY="true"; shift ;;
    --listing) LISTING="${2:?--listing needs an id}"; shift 2 ;;
    --dry-run) DRY="1"; shift ;;
    -h|--help) usage; exit 0 ;;
    *) fail "unknown option $1 (see --help)" ;;
  esac
done

command -v curl >/dev/null 2>&1 || fail "curl is required"
[ -n "${PEAKSTONE_TOKEN:-}" ] || [ -n "$DRY" ] || fail "set PEAKSTONE_TOKEN (an API token with releases:write)"
[ -n "$LISTING" ] || fail "set PEAKSTONE_LISTING_ID or pass --listing"

# Version: flag, then the tag of the common CI systems, then git.
if [ -z "$VERSION" ]; then
  TAG="${CI_COMMIT_TAG:-${CI_TAG:-${DRONE_TAG:-${BITBUCKET_TAG:-${TAG_NAME:-}}}}}"
  if [ -z "$TAG" ] && [ "${GITHUB_REF_TYPE:-}" = "tag" ]; then TAG="${GITHUB_REF_NAME:-}"; fi
  if [ -z "$TAG" ] && command -v git >/dev/null 2>&1; then TAG="$(git describe --tags --exact-match 2>/dev/null || true)"; fi
  [ -n "$TAG" ] || fail "no version: run on a tag (v1.2.3) or pass --version"
  VERSION="${TAG#v}"
fi

if [ -z "$CHANNEL" ]; then
  case "$(printf '%s' "$VERSION" | tr '[:upper:]' '[:lower:]')" in
    *alpha*|*snapshot*|*dev*) CHANNEL="alpha" ;;
    *beta*|*-rc*|*pre*) CHANNEL="beta" ;;
    *) CHANNEL="stable" ;;
  esac
fi
case "$CHANNEL" in stable|beta|alpha) ;; *) fail "--channel must be stable, beta or alpha" ;; esac

# Jar: flag, else the newest real jar Gradle or Maven produced (not -plain, -sources, -javadoc or Maven's original-).
if [ -z "$JAR" ]; then
  JAR="$(ls -t build/libs/*.jar target/*.jar 2>/dev/null | grep -vE -- '-(plain|sources|javadoc)\.jar$|/original-[^/]*\.jar$' | head -n 1 || true)"
  [ -n "$JAR" ] || fail "no jar found in build/libs or target: build first or pass --jar"
fi
[ -f "$JAR" ] || fail "jar not found: $JAR"

if [ -n "$NOTES_FILE" ]; then
  [ -f "$NOTES_FILE" ] || fail "notes file not found: $NOTES_FILE"
  NOTES="$(cat "$NOTES_FILE")"
fi

echo "peakstone: $JAR as $VERSION ($CHANNEL${SECURITY:+, security fix}) to listing $LISTING"
[ -z "$DRY" ] || { echo "peakstone: dry run, nothing uploaded"; exit 0; }

OUT="$(mktemp)"
trap 'rm -f "$OUT"' EXIT
set -- -sS -o "$OUT" -w '%{http_code}' -X POST "$PEAKSTONE_URL/api/v1/listings/$LISTING/releases" \
  -H "Authorization: Bearer $PEAKSTONE_TOKEN" -H "User-Agent: peakstone.sh/1" \
  -F "file=@$JAR" -F "version=$VERSION" -F "channel=$CHANNEL"
[ -z "$NOTES" ] || set -- "$@" -F "notes=$NOTES"
[ -z "$SECURITY" ] || set -- "$@" -F "security_fix=true"
CODE="$(curl "$@")" || fail "could not reach $PEAKSTONE_URL"

BODY="$(cat "$OUT")"
MESSAGE="$(printf '%s' "$BODY" | sed -n 's/.*"message":"\([^"]*\)".*/\1/p' | head -n 1)"
[ -n "$MESSAGE" ] || MESSAGE="$(printf '%s' "$BODY" | sed -n 's/.*"error":"\([^"]*\)".*/\1/p' | head -n 1)"
case "$CODE" in
  2*) echo "peakstone: uploaded. ${MESSAGE:-It waits for review like any other release.}" ;;
  *) fail "upload refused ($CODE): ${MESSAGE:-$BODY}" ;;
esac
