#!/usr/bin/env bash

# Who this machine belongs to: git identity, GitHub, and an SSH key.
#
# Runs last, because gh and git-all arrive with install-packages. Everything here
# is driven by answers the interview collected before the run started, so nothing
# in this stage blocks waiting for input -- except `gh auth login`, which is an
# interactive browser flow by nature and only runs when it was asked for.
#
# Every value is optional. A blank answer means "keep whatever is already set",
# which is what makes this safe to re-run: the interview's prompts start empty
# every time by design, and an empty answer must never erase a correct name.

set -uo pipefail

log() { echo -e "\033[1;34m[INFO]\033[0m $*"; }

git_name="${PANAMA_GIT_NAME:-}"
git_email="${PANAMA_GIT_EMAIL:-}"
git_editor="${PANAMA_GIT_EDITOR:-}"

if [[ -n "$git_name" ]]; then
    git config --global user.name "$git_name"
    log "git user.name set to $git_name"
fi
if [[ -n "$git_email" ]]; then
    git config --global user.email "$git_email"
    log "git user.email set to $git_email"
fi
if [[ -n "$git_editor" ]]; then
    git config --global core.editor "$git_editor"
    log "git core.editor set to $git_editor"
fi

# Aliases and pull behaviour, carried over from sunhat. Setting these is
# idempotent, so they are applied unconditionally rather than asked about.
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.st status
git config --global pull.rebase true
log "git aliases and pull.rebase applied"

if [[ "${PANAMA_GH_LOGIN:-no}" == yes ]]; then
    if command -v gh >/dev/null 2>&1; then
        log "Signing in to GitHub"
        gh auth login || log "GitHub sign-in did not complete; run 'gh auth login' later"
    else
        log "gh is not installed; skipping GitHub sign-in"
    fi
fi

if [[ "${PANAMA_SSH_KEY:-no}" == yes ]]; then
    key="$HOME/.ssh/id_ed25519"
    if [[ -e "$key" ]]; then
        log "An SSH key already exists at $key; leaving it alone"
    else
        mkdir -p "$HOME/.ssh"
        chmod 700 "$HOME/.ssh"
        # No passphrase prompt: this stage runs inside an install that was
        # promised to need no attention. A key can be given a passphrase later
        # with ssh-keygen -p.
        ssh-keygen -t ed25519 -N "" -C "${git_email:-$USER@$(hostname)}" -f "$key" >/dev/null
        log "SSH key generated at $key"
        log "Public key: $(cat "$key.pub")"
    fi
fi
