#!/bin/bash
# Krill installer — https://krill.page/install.sh
#
#   curl -fsSL https://krill.page/install.sh | bash
#   curl -fsSL https://krill.page/install.sh | bash -s -- --release v0.1.2
#
# Fetches the release installer (packaging/install.sh) attached to the GitHub
# release and runs it: SHA-256 + codesign verification, /Applications/Krill.app,
# ~/.local/bin/krill symlink. All arguments are passed through.
set -euo pipefail

REPO="${KRILL_REPO:-craftowen/krill}"

[[ "$(uname -s)" == "Darwin" ]] || { echo "krill: macOS only" >&2; exit 2; }

WORK="$(mktemp -d "${TMPDIR:-/tmp}/krill-bootstrap.XXXXXXXX")"
trap 'rm -rf "${WORK}"' EXIT
SCRIPT="${WORK}/install.sh"

echo "==> Fetching Krill installer from github.com/${REPO}"
if ! curl -fsSL "https://github.com/${REPO}/releases/latest/download/install.sh" -o "${SCRIPT}" 2>/dev/null; then
    # Private repository: fall back to an authenticated gh CLI.
    command -v gh >/dev/null || {
        echo "krill: download failed and 'gh' was not found (brew install gh && gh auth login)" >&2
        exit 1
    }
    gh release download --repo "${REPO}" --pattern install.sh --dir "${WORK}" --clobber
fi

head -1 "${SCRIPT}" | grep -q '^#!' || { echo "krill: downloaded installer looks invalid" >&2; exit 1; }
exec bash "${SCRIPT}" --repo "${REPO}" "$@"
