#!/bin/bash

# Release installer for Piranha CLI.
# Usage:
#   curl -fsSL https://cli.piranha.sh/install.sh | sudo bash
#   curl -fsSL https://cli.piranha.sh/install.sh | sudo env PIRANHA_CLI_VERSION=0.0.1 bash

set -euo pipefail

RELEASE_BASE_URL="${PIRANHA_CLI_RELEASE_BASE_URL:-https://cli.piranha.sh}"
REQUESTED_VERSION="${PIRANHA_CLI_VERSION:-latest}"
TMP_DIR="$(mktemp -d)"
DEB_FILE="${TMP_DIR}/piranha-cli.deb"
TARBALL_FILE="${TMP_DIR}/piranha-cli.tar.gz"

cleanup() {
    rm -rf "${TMP_DIR}"
}

trap cleanup EXIT

if [[ "${EUID}" -ne 0 ]]; then
    echo "This script must be run as root (use sudo)." >&2
    exit 1
fi

command -v curl >/dev/null 2>&1 || {
    echo "curl is required but not installed." >&2
    exit 1
}

release_url() {
    local asset_name="$1"
    if [[ "${REQUESTED_VERSION}" == "latest" ]]; then
        printf '%s/%s\n' "${RELEASE_BASE_URL%/}" "${asset_name}"
    else
        printf '%s/%s/%s\n' "${RELEASE_BASE_URL%/}" "${REQUESTED_VERSION}" "${asset_name}"
    fi
}

install_from_deb() {
    local package_url
    if [[ "${REQUESTED_VERSION}" == "latest" ]]; then
        package_url="$(release_url 'piranha-cli_latest_all.deb')"
    else
        package_url="$(release_url "piranha-cli_${REQUESTED_VERSION}_all.deb")"
    fi

    echo "Downloading Debian package from ${package_url}"
    curl -fsSL "${package_url}" -o "${DEB_FILE}"
    dpkg -i "${DEB_FILE}" || {
        if command -v apt-get >/dev/null 2>&1; then
            apt-get update
            apt-get install -f -y
        else
            echo "dpkg reported missing dependencies and apt-get is not available." >&2
            exit 1
        fi
    }
}

install_from_tarball() {
    local tarball_url extracted_dir
    if [[ "${REQUESTED_VERSION}" == "latest" ]]; then
        tarball_url="$(release_url 'piranha-cli-latest.tar.gz')"
    else
        tarball_url="$(release_url "piranha-cli-${REQUESTED_VERSION}.tar.gz")"
    fi

    echo "Falling back to tarball install from ${tarball_url}"
    command -v tar >/dev/null 2>&1 || {
        echo "tar is required for the fallback install path." >&2
        exit 1
    }
    command -v php >/dev/null 2>&1 || {
        echo "php is required for the fallback install path." >&2
        exit 1
    }

    curl -fsSL "${tarball_url}" -o "${TARBALL_FILE}"
    tar -xzf "${TARBALL_FILE}" -C "${TMP_DIR}"
    extracted_dir="$(find "${TMP_DIR}" -maxdepth 1 -mindepth 1 -type d -name 'piranha-cli*' | head -n 1)"
    if [[ -z "${extracted_dir}" ]]; then
        echo "Could not find extracted Piranha CLI directory." >&2
        exit 1
    fi

    cd "${extracted_dir}"
    php install-silent
}

echo "Installing Piranha CLI ${REQUESTED_VERSION}"

if command -v dpkg >/dev/null 2>&1; then
    install_from_deb || install_from_tarball
else
    install_from_tarball
fi

echo "Piranha CLI installed."
echo "Usage:"
echo "  piranha --version"
echo "  piranha --help"
echo "  piranha ai list -yg"
