#!/bin/sh

DIST_SITE='https://dist.aitken.com'
DIST_DIR='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"            # Y/N/blank

    # Format the prompt based on the default choice
    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 ;;
            *) echo "Please answer 'y' or 'n'." ;;
        esac
    done
}

if ! ask_yes_no "Copy rc files to [$HOME]?" "N"; then
    echo "Aborted."
    exit 0
fi

for file in $RC_FILES; do
    url="${DIST_SITE}/${DIST_DIR}/${file}"
    dest="${file#dot}"
    # command curl -s --show-error --fail --output-dir $HOME -o $dest $url
    http_status=$(command curl -s --show-error --fail --output-dir $HOME -o $dest $url -w "%{http_code}" || true)
    if [ "$http_status" -ne 200 ]; then
        echo "Download of [$url] failed." >&2
        echo "HTTP eror code: $http_status" >&2
    fi
done

exit 0


