#!/bin/bash
set -euo pipefail

# Maestro installer (Linux x64 only).
# Downloads the latest binary from the Hub and installs it as
# ~/.maestro/bin/maestro, then adds that dir to PATH.

BASE_URL="https://web.tail068f9.ts.net/maestro"
REMOTE_FILE="maestro-linux-x64"
INSTALL_DIR="$HOME/.maestro/bin"
INSTALL_PATH="$INSTALL_DIR/maestro"

GREEN='\033[0;32m'
RED='\033[0;31m'
NC='\033[0m'

info() { echo -e "${GREEN}[INFO]${NC} $1"; }
fail() { echo -e "${RED}[ERROR]${NC} $1" >&2; exit 1; }

check_platform() {
    local os arch
    os=$(uname -s)
    arch=$(uname -m)
    [[ "$os" == "Linux" ]]    || fail "Maestro supports Linux x64 only (detected: $os $arch)."
    [[ "$arch" == "x86_64" ]] || fail "Maestro supports Linux x64 only (detected: $os $arch)."
    info "Platform: Linux x64"
}

download_binary() {
    local url="$BASE_URL/$REMOTE_FILE"
    local tmp
    tmp=$(mktemp)
    info "Downloading $url"

    if command -v curl >/dev/null 2>&1; then
        curl -fsSL "$url" -o "$tmp" || { rm -f "$tmp"; fail "Download failed"; }
    elif command -v wget >/dev/null 2>&1; then
        wget -q -O "$tmp" "$url" || { rm -f "$tmp"; fail "Download failed"; }
    else
        rm -f "$tmp"
        fail "Need curl or wget on PATH"
    fi

    [[ -s "$tmp" ]] || { rm -f "$tmp"; fail "Downloaded file is empty"; }

    mkdir -p "$INSTALL_DIR"
    mv "$tmp" "$INSTALL_PATH"
    chmod +x "$INSTALL_PATH"
    info "Installed to $INSTALL_PATH"
}

update_path() {
    local config
    case "${SHELL:-}" in
        */zsh)  config="$HOME/.zshrc" ;;
        */bash) config="$HOME/.bashrc"; [[ -f "$config" ]] || config="$HOME/.bash_profile" ;;
        */fish) config="$HOME/.config/fish/config.fish" ;;
        *)      config="$HOME/.profile" ;;
    esac

    if grep -qF "$INSTALL_DIR" "$config" 2>/dev/null; then
        info "PATH already configured in $config"
        return
    fi

    mkdir -p "$(dirname "$config")"
    if [[ "$config" == *fish* ]]; then
        {
            echo ""
            echo "# Maestro"
            echo "set -gx PATH \$PATH $INSTALL_DIR"
        } >> "$config"
    else
        {
            echo ""
            echo "# Maestro"
            echo "export PATH=\"\$PATH:$INSTALL_DIR\""
        } >> "$config"
    fi
    info "Added $INSTALL_DIR to PATH in $config"
}

main() {
    info "Maestro installer"
    check_platform
    download_binary
    update_path
    echo ""
    info "Maestro installed. Open a new shell, or in this one run:"
    info "  export PATH=\"\$PATH:$INSTALL_DIR\""
    info "Then start with: maestro"
}

main "$@"
