#!/bin/bash
# Shared configuration installer; safe to source from the platform installers.

GIST_RAW_BASE="${GIST_RAW_BASE:-https://opengist.resetrix.work/weehong/f0d940c3c1214bf5b7996195199fdc09/raw/HEAD}"
CONFIG_FILES=(
    ".alias"
    ".func"
    ".pathrc"
    ".sourcerc"
    ".vimrc"
    ".zshrc"
    ".config/starship.toml"
    ".config/ai-commit-prompt.txt"
    ".config/ai-commit-split-prompt.txt"
    ".config/opencode/agents/ai-commit.md"
    ".config/opencode/agents/ai-commit-plan.md"
)

download_config() (
    # A subshell keeps temporary-file traps out of the caller's shell.
    local file="$1" remote_name target tmp
    remote_name="${file##*/}"
    remote_name="${remote_name#.}"
    target="$HOME/$file"
    mkdir -p "$(dirname "$target")" || return 1
    tmp="$(mktemp "${target}.tmp.XXXXXX")" || return 1
    trap 'rm -f "$tmp"' EXIT
    trap 'exit 1' HUP INT TERM

    printf 'Downloading %s...\n' "$file"
    if curl -fsSL "${GIST_RAW_BASE%/}/$remote_name" -o "$tmp" &&
        [[ -s "$tmp" ]] && mv "$tmp" "$target"; then
        printf 'Successfully updated %s\n' "$target"
    else
        printf 'Error: Failed to install %s\n' "$file" >&2
        return 1
    fi
)

download_configs() {
    local file failed=0
    for file in "${CONFIG_FILES[@]}"; do
        download_config "$file" || failed=1
    done
    if [[ "$failed" -ne 0 ]]; then
        printf 'Configuration download completed with errors.\n' >&2
        return 1
    fi
    printf 'Done! All configuration files have been replaced.\n'
}

configure_zshrc() {
    download_config .zshrc
}

if [[ "${BASH_SOURCE[0]:-$0}" == "$0" ]]; then
    set -euo pipefail
    download_configs
fi
