#!/bin/sh

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/vim-colorschemes'
DEST_DIR="$HOME/.vim/colors"
COLORSCHEME_FILES="
    nord.vim
    solarized.vim
    tokyonight.vim
"


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 "Copy vim color schemes 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; }

for file in $COLORSCHEME_FILES; 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
