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

# Axottle public installation bootstrap. The full installer and panel archive
# are both fetched from the exact release tag selected below.
REPOSITORY="Axottle/axottle-releases"
RELEASE="latest"
FORWARD=()

fail() {
  echo "axottle installer: $*" >&2
  exit 1
}

while (($#)); do
  case "$1" in
    --version)
      (($# >= 2)) || fail "--version requires a tag or 'latest'"
      RELEASE="$2"
      shift 2
      ;;
    --repo|--release|--artifact|--artifact-url)
      fail "release source is managed by get.axottle.com; use --version only"
      ;;
    --)
      shift
      FORWARD+=("$@")
      break
      ;;
    *)
      FORWARD+=("$1")
      shift
      ;;
  esac
done

command -v curl >/dev/null 2>&1 || fail "curl is required"

AUTH=()
TOKEN="${GITHUB_TOKEN:-${GH_TOKEN:-}}"
if [[ -n "$TOKEN" ]]; then
  AUTH=(-H "Authorization: Bearer $TOKEN")
fi

if [[ "$RELEASE" == "latest" ]]; then
  API_URL="https://api.github.com/repos/$REPOSITORY/releases/latest"
else
  API_URL="https://api.github.com/repos/$REPOSITORY/releases/tags/$RELEASE"
fi

RELEASE_JSON="$(curl -fsSL "${AUTH[@]}" -H "Accept: application/vnd.github+json" "$API_URL")" \
  || fail "cannot resolve release '$RELEASE' for $REPOSITORY"
TAG="$(printf '%s' "$RELEASE_JSON" | sed -n 's/.*"tag_name"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p')"
[[ -n "$TAG" ]] || fail "GitHub response did not contain a release tag"

TMP="$(mktemp -d -t axottle-install-XXXXXX)"
trap 'rm -rf "$TMP"' EXIT
INSTALLER="$TMP/install.sh"
INSTALLER_URL="$(printf '%s\n' "$RELEASE_JSON" | awk '
  /"name"[[:space:]]*:[[:space:]]*"axottle-installer\.sh"/ { found=1 }
  found && /"browser_download_url"[[:space:]]*:/ {
    url=$0
    sub(/^.*"browser_download_url"[[:space:]]*:[[:space:]]*"/, "", url)
    sub(/".*$/, "", url)
    print url
    exit
  }
')"
[[ -n "$INSTALLER_URL" ]] || fail "release $TAG does not include the axottle-installer.sh asset"

curl -fsSL "${AUTH[@]}" "$INSTALLER_URL" -o "$INSTALLER" \
  || fail "cannot download installer for $TAG"

exec bash "$INSTALLER" --repo "$REPOSITORY" --release "$TAG" "${FORWARD[@]}"
