#!/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/rc-files'
RC_FILES="
    dot.bash_logout
    dot.bash_profile
    dot.bashrc
    dot.inputrc
    dot.nexrc
    dot.profile
    dot.selected_editor
    dot.vimrc
"


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 rc files to [$HOME]?" "N"; then
        printf '%s\n' "Aborted."
        exit 0
    fi
fi

for file in $RC_FILES; do
    url="${DIST_SITE}/${DIST_DIR}/${file}"
    dest="${HOME}/${file#dot}"
    http_status=$(command curl -s --show-error --fail \
        -o "$dest" "$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
