#!/usr/bin/env bash
# Monoceros devcontainer feature: github-cli.
#
# Installs the official GitHub CLI (`gh`) from cli.github.com's apt
# repository. When the `token` option is set, the value is exposed
# as GH_TOKEN via /etc/profile.d so every login shell sees an
# authenticated `gh`. Without a token, `gh` is installed but
# unauthenticated; the builder can run `gh auth login` once
# interactively and the resulting `~/.config/gh/` state is
# persisted via Monoceros' bind-mount.

set -euo pipefail

APITOKEN="${APITOKEN:-}"

echo "[github-cli] installing gh from cli.github.com apt repo"

# Per https://cli.github.com/manual/installation (Debian/Ubuntu path).
type -p curl >/dev/null || {
  apt-get update
  apt-get install -y curl
}

curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg \
  | dd of=/usr/share/keyrings/githubcli-archive-keyring.gpg
chmod go+r /usr/share/keyrings/githubcli-archive-keyring.gpg

mkdir -p -m 755 /etc/apt/sources.list.d
ARCH="$(dpkg --print-architecture)"
echo "deb [arch=${ARCH} signed-by=/usr/share/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" \
  > /etc/apt/sources.list.d/github-cli.list

apt-get update
apt-get install -y --no-install-recommends gh

gh --version >/dev/null 2>&1 || {
  echo "[github-cli] ERROR: install completed but \`gh\` is not on PATH" >&2
  exit 1
}

if [ -n "${APITOKEN}" ]; then
  cat >/etc/profile.d/github-cli.sh <<EOF
# Auto-generated by the Monoceros github-cli feature. Exports
# GH_TOKEN so the GitHub CLI authenticates non-interactively.
export GH_TOKEN='${APITOKEN}'
EOF
  chmod 0644 /etc/profile.d/github-cli.sh
  echo "[github-cli] apiToken wired via /etc/profile.d/ → \`gh\` authenticated in login shells"
else
  echo "[github-cli] no apiToken set — run \`gh auth login\` once in the container; auth state persists under ~/.config/gh"
fi

echo "[github-cli] done"
