#!/bin/sh
set -e

PROJECT_NAME="clnstrt-tool"
REPO_URL="https://get.clnstrt.dev"

# Color codes for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Default install directory
INSTALL_DIR="/usr/local/bin"

# Parse command line arguments
while [ $# -gt 0 ]; do
    case $1 in
        -b)
            INSTALL_DIR="$2"
            shift 2
            ;;
        --help)
            echo "Usage: curl -sSfL https://get.clnstrt.dev | sudo sh -s -- [-b <install_dir>]"
            echo ""
            echo "Options:"
            echo "  -b <install_dir>    Install binary to <install_dir> (default: /usr/local/bin)"
            echo ""
            echo "Examples:"
            echo "  # Install to default location"
            echo "  curl -sSfL https://get.clnstrt.dev | sudo sh"
            echo ""
            echo "  # Install to custom location"
            echo "  curl -sSfL https://get.clnstrt.dev | sudo sh -s -- -b /usr/local/bin"
            exit 0
            ;;
        *)
            shift
            ;;
    esac
done

# Create temp directory
TMPDIR=$(mktemp -d)
trap 'rm -rf "$TMPDIR"' EXIT

echo "Installing ${PROJECT_NAME}..."

# Download binary (always latest from root)
BINARY_URL="${REPO_URL}/${PROJECT_NAME}"

# Suppress the downloading message
if ! curl -sSfL "${BINARY_URL}" -o "${TMPDIR}/${PROJECT_NAME}"; then
    printf "${RED}Error: Failed to download ${PROJECT_NAME}${NC}\n"
    exit 1
fi

# Make binary executable
chmod +x "${TMPDIR}/${PROJECT_NAME}"

# Check if install directory is writable
if [ -w "${INSTALL_DIR}" ]; then
    SUDO=""
else
    # Check if running as root
    if [ "$(id -u)" -eq 0 ]; then
        SUDO=""
    else
        SUDO="sudo"
        printf "${YELLOW}Installation to ${INSTALL_DIR} requires sudo privileges${NC}\n"
    fi
fi

# Install binary and suppress installation status messages
$SUDO mkdir -p "${INSTALL_DIR}"
$SUDO mv "${TMPDIR}/${PROJECT_NAME}" "${INSTALL_DIR}/${PROJECT_NAME}"

# Verify installation without printing the "installed successfully" message
if command -v ${PROJECT_NAME} >/dev/null 2>&1; then
    printf "${GREEN}${PROJECT_NAME} installed successfully!${NC}\n"
else
    printf "${YELLOW}${PROJECT_NAME} installed to ${INSTALL_DIR}${NC}\n"
    printf "${YELLOW}You may need to add ${INSTALL_DIR} to your PATH${NC}\n"
fi

