#!/bin/bash
set -euo pipefail

# Configuration
GIST_RAW_BASE="https://opengist.resetrix.work/weehong/f0d940c3c1214bf5b7996195199fdc09/raw/HEAD"
CONFIG_FILES=(
    ".alias"
    ".func"
    ".pathrc"
    ".sourcerc"
    ".vimrc"
    ".zshrc"
    ".config/starship.toml"
    ".config/opencode/agents/ai-commit.md"
)

echo "Starting configuration download..."
download_failed=0

for f in "${CONFIG_FILES[@]}"; do
    # Remove the leading dot for the URL path
    remote_name="${f#.}"
    [[ "$f" == ".config/starship.toml" ]] && remote_name="starship.toml"
    [[ "$f" == ".config/opencode/agents/ai-commit.md" ]] && remote_name="ai-commit.md"
    url="$GIST_RAW_BASE/$remote_name"
    target="$HOME/$f"
    tmp="${target}.tmp.$$"

    echo "Downloading $f..."
    mkdir -p "$(dirname "$target")"
    
    # Use -f to fail silently on server errors, -s for silent, -L to follow redirects
    if curl -fsSL "$url" -o "$tmp" && mv "$tmp" "$target"; then
        echo "Successfully updated $target"
    else
        rm -f "$tmp"
        echo "Error: Failed to download $f from $url" >&2
        download_failed=1
    fi
done

if [ "$download_failed" -ne 0 ]; then
    echo "Configuration download completed with errors." >&2
    exit 1
fi

echo "Done! All configuration files have been replaced."
