#!/usr/bin/env bash
set -euo pipefail

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m'

log_info()  { echo -e "${CYAN}[INFO]${NC}  $*"; }
log_ok()    { echo -e "${GREEN}[OK]${NC}    $*"; }
log_warn()  { echo -e "${YELLOW}[WARN]${NC}  $*"; }
log_error() { echo -e "${RED}[ERROR]${NC} $*"; }

install_rust() {
    log_info "Rust is not installed. Downloading and installing the latest Rust toolchain..."
    if command -v curl >/dev/null 2>&1; then
        curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain stable
    elif command -v wget >/dev/null 2>&1; then
        wget -qO- https://sh.rustup.rs | sh -s -- -y --default-toolchain stable
    else
        log_error "Neither curl nor wget found. Please install one of them and re-run this script."
        exit 1
    fi
    source "$HOME/.cargo/env"
    log_ok "Rust and Cargo installed successfully."
}

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

echo ""
echo -e "${CYAN}╔══════════════════════════════════════════════════════════╗${NC}"
echo -e "${CYAN}║                       crtin                              ║${NC}"
echo -e "${CYAN}║                   Linux Installer                        ║${NC}"
echo -e "${CYAN}╚══════════════════════════════════════════════════════════╝${NC}"
echo ""

if command -v cargo >/dev/null 2>&1 && command -v rustc >/dev/null 2>&1; then
    log_ok "Rust $(rustc --version | cut -d' ' -f2) and Cargo $(cargo --version | cut -d' ' -f2) found."
else
    install_rust
fi

if ! command -v cargo >/dev/null 2>&1; then
    log_error "Cargo still not available after installation attempt. Exiting."
    exit 1
fi

log_info "Building crtin (release profile)..."
cargo build --release

log_ok "Build completed successfully."

BIN_PATH="$PWD/target/release/crtin"

install_to=""
if [ -w /usr/local/bin ]; then
    install_to="/usr/local/bin"
elif [ -d "$HOME/.local/bin" ] && [ -w "$HOME/.local/bin" ]; then
    install_to="$HOME/.local/bin"
else
    mkdir -p "$HOME/.local/bin" && install_to="$HOME/.local/bin"
fi

cp "$BIN_PATH" "$install_to/crtin"
chmod +x "$install_to/crtin"

if [[ ":$PATH:" != *":$install_to:"* ]]; then
    log_warn "$install_to is not in your PATH."
    echo "Add the following line to your ~/.bashrc or ~/.profile:"
    echo "  export PATH=\"$install_to:\$PATH\""
    echo "Then run: source ~/.bashrc (or restart your shell)"
fi

log_ok "crtin installed to $install_to/crtin"
echo ""
echo -e "${GREEN}Installation complete. Run 'crtin --help' to get started.${NC}"
