#!/usr/bin/env bash
#
# monats installer
#
# Interactive:
#   curl -fsSL https://raw.githubusercontent.com/demec/monats/main/install.sh | bash
#
# Non-interactive:
#   curl -fsSL https://raw.githubusercontent.com/demec/monats/main/install.sh | bash -s -- --token ghp_xxx
#
# Options:
#   --token, -t     GitHub PAT with repo scope (only needed if repo is private)
#   --version, -v   Release version (default: latest)
#
# Environment:
#   MONATS_TOKEN    Alternative to --token
#
set -euo pipefail

REPO="demec/monats"
INSTALL_DIR="/usr/local/bin"

TOKEN=""
VERSION=""

while [[ $# -gt 0 ]]; do
  case "$1" in
    --token|-t)   TOKEN="$2"; shift 2 ;;
    --version|-v) VERSION="$2"; shift 2 ;;
    --help|-h)
      sed -n '2,15p' "$0" | sed 's/^# \{0,1\}//'
      exit 0 ;;
    *) echo "Unknown option: $1" >&2; exit 1 ;;
  esac
done

TOKEN="${TOKEN:-${MONATS_TOKEN:-}}"

if ! command -v jq &>/dev/null; then
  echo "Error: jq is required. Install with: sudo apt-get install -y jq" >&2
  exit 1
fi

auth_args=()
if [[ -n "$TOKEN" ]]; then
  auth_args=(-H "Authorization: token ${TOKEN}")
fi

gh_api() {
  curl -fsSL "${auth_args[@]}" -H "Accept: application/vnd.github+json" "$@"
}

gh_download() {
  curl -fsSL "${auth_args[@]}" -H "Accept: application/octet-stream" "$@"
}

case "$(uname -m)" in
  x86_64)  ARCH_LABEL="amd64" ;;
  aarch64) ARCH_LABEL="arm64" ;;
  *) echo "Error: unsupported architecture: $(uname -m)" >&2; exit 1 ;;
esac

USE_DEB=false
if command -v dpkg &>/dev/null && command -v apt-get &>/dev/null; then
  USE_DEB=true
fi

if [[ -n "$VERSION" ]]; then
  TAG="${VERSION#v}"; TAG="v${TAG}"
  echo "Fetching release ${TAG}..."
  RELEASE_JSON="$(gh_api "https://api.github.com/repos/${REPO}/releases/tags/${TAG}")"
else
  echo "Fetching latest release..."
  RELEASE_JSON="$(gh_api "https://api.github.com/repos/${REPO}/releases/latest")"
fi

TAG="$(echo "$RELEASE_JSON" | jq -r '.tag_name')"
[[ -z "$TAG" || "$TAG" == "null" ]] && { echo "Error: no release found." >&2; exit 1; }
echo "Version: ${TAG}"

if $USE_DEB; then PATTERN='\.deb$';      LABEL='.deb package'
else              PATTERN='\.AppImage$'; LABEL='AppImage'; fi

echo "Looking for ${LABEL} (${ARCH_LABEL})..."
ASSET_INFO="$(echo "$RELEASE_JSON" | jq -r \
  --arg p "$PATTERN" --arg a "$ARCH_LABEL" \
  '[.assets[] | select(.name | test($p)) | select(.name | test($a))] | first | "\(.url)\t\(.name)"')"

if [[ -z "$ASSET_INFO" || "$ASSET_INFO" == "null"* ]]; then
  ASSET_INFO="$(echo "$RELEASE_JSON" | jq -r \
    --arg p "$PATTERN" \
    '[.assets[] | select(.name | test($p))] | first | "\(.url)\t\(.name)"')"
fi

URL="$(echo "$ASSET_INFO" | cut -f1)"
NAME="$(echo "$ASSET_INFO" | cut -f2)"
if [[ -z "$URL" || "$URL" == "null" ]]; then
  echo "Error: no matching asset in ${TAG}." >&2
  echo "$RELEASE_JSON" | jq -r '.assets[].name' | sed 's/^/  /' >&2
  exit 1
fi

TMPDIR="$(mktemp -d)"
trap 'rm -rf "$TMPDIR"' EXIT

echo "Downloading ${NAME}..."
gh_download "$URL" -o "${TMPDIR}/${NAME}"

if $USE_DEB; then
  echo "Installing .deb..."
  sudo dpkg -i "${TMPDIR}/${NAME}"
  sudo apt-get install -f -y
  echo "Installed monats ${TAG} via dpkg."
else
  echo "Installing AppImage to ${INSTALL_DIR}/monats..."
  chmod +x "${TMPDIR}/${NAME}"
  sudo mv "${TMPDIR}/${NAME}" "${INSTALL_DIR}/monats"
  echo "Installed monats ${TAG}."
fi

echo ""
echo "Done."

