#!/bin/sh
#
# Installs glow config file (glow.yml) and Nord color scheme (nord.json).
# Run as the target user (not root) so files land in the correct $HOME.
#
# To overwrite an existing glow config, set OVERWRITE_GLOW_CONFIG=1:
#   OVERWRITE_GLOW_CONFIG=1 sh install-glow-config.sh
#   make glow-config-fresh   (uses the same env var)

PATH=/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin
export PATH
set -e
trap '[ $? -eq 0 ] || printf "ERROR: %s did not complete successfully.\n" "$0" >&2' EXIT
trap 'exit 1' INT HUP TERM

DIST_SITE='https://dist.aitken.com'
DIST_DIR='local/glow-config'
case "$(uname -s)" in
    Darwin) DEST_DIR="$HOME/Library/Preferences/glow" ;;
    *)      DEST_DIR="$HOME/.config/glow" ;;
esac
GLOW_THEMES="nord.json"


ask_yes_no() {
    _prompt="$1"
    _default="$2"
    case "$_default" in
        [Yy]*) _hint=" [Y/n]: " ;;
        [Nn]*) _hint=" [y/N]: " ;;
        *)     _hint=" (y/n): " ;;
    esac
    while true; do
        printf '%s%s' "$_prompt" "$_hint"
        read -r _response
        if [ -z "$_response" ]; then
            case "$_default" in
                [Yy]*) return 0 ;;
                [Nn]*) return 1 ;;
            esac
        fi
        case "$_response" in
            [Yy]*) return 0 ;;
            [Nn]*) return 1 ;;
            *) printf '%s\n' "Please answer 'y' or 'n'." ;;
        esac
    done
}

# When run via "curl url | sh", stdin is the pipe and ask_yes_no would
# get EOF immediately.  Skip the prompt and proceed in non-interactive mode.
if [ -t 0 ]; then
    if ! ask_yes_no "Install glow config to [$DEST_DIR]?" "N"; then
        printf '%s\n' "Aborted."
        exit 0
    fi
fi

mkdir -p "$DEST_DIR" || { printf 'Error: could not create %s\n' "$DEST_DIR" >&2; exit 1; }

# Install glow config -- skip if already present unless OVERWRITE_GLOW_CONFIG is set
_config="$DEST_DIR/glow.yml"
if [ -f "$_config" ] && [ -z "$OVERWRITE_GLOW_CONFIG" ]; then
    printf 'glow config already exists at %s -- skipping (set OVERWRITE_GLOW_CONFIG=1 to overwrite)\n' "$_config"
else
    http_status=$(command curl -s --show-error --fail \
        -o "$_config" "${DIST_SITE}/${DIST_DIR}/glow.yml" -w "%{http_code}" || true)
    if [ "$http_status" -ne 200 ]; then
        printf 'Download of glow config failed (HTTP %s)\n' "$http_status" >&2
    else
        sed "s|__GLOW_CONFIG_DIR__|${DEST_DIR}|" "$_config" > "${_config}.tmp" \
            && mv "${_config}.tmp" "$_config"
    fi
fi

# Install themes
for file in $GLOW_THEMES; do
    url="${DIST_SITE}/${DIST_DIR}/${file}"
    http_status=$(command curl -s --show-error --fail \
        -o "${DEST_DIR}/${file}" "$url" -w "%{http_code}" || true)
    if [ "$http_status" -ne 200 ]; then
        printf 'Download of [%s] failed (HTTP %s)\n' "$url" "$http_status" >&2
    fi
done

exit 0
