#!/bin/sh
# Install dbt-index (beta).
#
# Usage:
#   curl -fsSL https://public.cdn.getdbt.com/fs/install/install-index.sh | sh
#   curl -fsSL .../install-index.sh | sh -s -- --version 1.0.0-dev.42
#   curl -fsSL .../install-index.sh | sh -s -- --to ~/.local/bin

set -eu

td=""
cleanup() { [ -n "$td" ] && rm -rf "$td"; }
trap cleanup EXIT

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

log() { printf "install-index.sh: %s\n" "$1"; }
log_grey() { printf "${GRAY}install-index.sh: %s${NC}\n" "$1"; }
log_green() { printf "${GREEN}install-index.sh: %s${NC}\n" "$1"; }
err_and_exit() { printf "${RED}ERROR: %s${NC}\n" "$1"; exit 1; }
need() { command -v "$1" >/dev/null 2>&1 || err_and_exit "need $1 (command not found)"; }

detect_target() {
    arch=$(uname -m)
    os=$(uname -s | tr '[:upper:]' '[:lower:]')
    case "$os" in
        linux)
            case "$arch" in
                arm64|aarch64) echo "aarch64-unknown-linux-gnu" ;;
                x86_64)        echo "x86_64-unknown-linux-gnu" ;;
                *) err_and_exit "Unsupported architecture: $arch" ;;
            esac ;;
        darwin)
            case "$arch" in
                arm64) echo "aarch64-apple-darwin" ;;
                *)     echo "x86_64-apple-darwin" ;;
            esac ;;
        *) err_and_exit "Unsupported OS: $os" ;;
    esac
}

# Fetch semver published by the release workflow
resolve_latest_version() {
    cdn="$1"
    url="https://${cdn}/dbt-index/LATEST"
    if ! curl -fsSL "$url" -o "$td/latest.txt" 2>/dev/null; then
        err_and_exit "Failed to fetch $url" "Pass --version explicitly, or wait until a release has uploaded LATEST."
    fi
    head -1 "$td/latest.txt" | tr -d '\r' | sed 's/^[[:space:]]*//;s/[[:space:]]*$//'
}

version=""
dest=""

while [ $# -gt 0 ]; do
    case "$1" in
        --version) shift; version="$1" ;;
        --to)      shift; dest="$1" ;;
        --help|-h)
            cat <<EOF
Usage: install-index.sh [--version VERSION | latest] [--to DIRECTORY]

Options:
    --version VERSION   Semver to install, or "latest" (default: resolve from CDN LATEST file).
    --to DIRECTORY    Install directory (default: ~/.local/bin)

Examples:
    curl -fsSL https://public.cdn.getdbt.com/fs/install/install-index.sh | sh
    curl -fsSL .../install-index.sh | sh -s -- --version 1.0.0-dev.42

Uninstall:
    curl -fsSL https://public.cdn.getdbt.com/fs/install/uninstall-index.sh | sh
EOF
            exit 0
            ;;
        *) err_and_exit "Unknown option: $1 (use --help for usage)" ;;
    esac
    shift
done

need curl
need tar

td=$(mktemp -d || mktemp -d -t tmp)

cdn="public.cdn.getdbt.com"
ver_lower=$(printf '%s' "$version" | tr '[:upper:]' '[:lower:]')
if [ -z "$version" ] || [ "$ver_lower" = "latest" ]; then
    log_grey "Resolving latest dbt-index version from CDN..."
    version=$(resolve_latest_version "$cdn")
    [ -n "$version" ] || err_and_exit "Empty version from LATEST"
    log_grey "Using version: $version"
fi

dest="${dest:-$HOME/.local/bin}"
target=$(detect_target)
url="https://${cdn}/dbt-index/dbt-index-v${version}-${target}.tar.gz"

log_grey "Version:  $version"
log_grey "Platform: $target"
log_grey "Dest:     $dest"
log_grey "URL:      $url"
log ""

log_grey "Downloading..."
curl -fsSL "$url" -o "$td/archive.tar.gz" || err_and_exit "Failed to download from $url"

log_grey "Extracting..."
tar -xzf "$td/archive.tar.gz" -C "$td" || err_and_exit "Failed to extract archive"

binary=$(find "$td" -name "dbt-index" -type f | head -1)
[ -n "$binary" ] || err_and_exit "dbt-index binary not found in archive"

mkdir -p "$dest" || err_and_exit "Failed to create directory: $dest"
install -m 755 "$binary" "$dest/dbt-index" || err_and_exit "Failed to install dbt-index"

log ""
log_green "Installed dbt-index v${version} to $dest/dbt-index"
log ""
log "Run: $dest/dbt-index --help"
