#!/bin/sh
set -e

# kl installer — fetches the latest binary from dashboard.stangebaum.ch
# Usage:
#   curl -sSL https://kl.stangebaum.ch | sh

BINARY_URL="https://dashboard.stangebaum.ch/files/kl/kl"

# --- Detect root vs user ---
if [ "$(id -u)" -eq 0 ]; then
    INSTALL_DIR="/usr/local/bin"
else
    INSTALL_DIR="$HOME/.local/bin"
fi

# --- Create install dir ---
mkdir -p "$INSTALL_DIR"

# --- Download binary ---
download() {
    if command -v curl >/dev/null 2>&1; then
        curl -sSL "$1" -o "$2"
    elif command -v wget >/dev/null 2>&1; then
        wget -q "$1" -O "$2"
    else
        echo "Error: neither curl nor wget found. Please install one and retry." >&2
        exit 1
    fi
}

echo "Downloading kl..."
download "$BINARY_URL" "$INSTALL_DIR/kl"
chmod 755 "$INSTALL_DIR/kl"

# --- Check PATH ---
in_path() {
    case ":$PATH:" in
        *:"$1":*) return 0 ;;
        *) return 1 ;;
    esac
}

echo ""
echo "kl installed to $INSTALL_DIR/kl"

if in_path "$INSTALL_DIR"; then
    echo "Run 'kl version' to verify."
else
    echo ""
    echo "Run 'kl self update-path' to add $INSTALL_DIR to your PATH."
fi
