#!/bin/bash

set -e

OS="$(uname -s)"
OS_NAME=""
ARCH=""
BINARY_NAME="bluearch"

echo_ascii_art() {
  echo ' ____   _                                     _'
  echo '|  _ \ | |                 /\                | |'
  echo '| |_) || | _   _   ___    /  \    _ __   ___ | |__'
  echo '|  _ < | || | | | / _ \  / /\ \  | '"'"'__| / __|| '"'"'_ \'
  echo '| |_) || || |_| ||  __/ / ____ \ | |   | (__ | | | |'
  echo '|____/ |_| \____| \___|/_/    \_\|_|    \___||_| |_|'
  echo
}

if [ "$OS" = "Darwin" ]; then
    INSTALL_DIR="$HOME/Library/Application Support/$BINARY_NAME/bin"
    ARCH="arm64"
    OS_NAME="macos"
elif [ "$OS" = "Linux" ]; then
    INSTALL_DIR="$HOME/.local/bin"
    ARCH="x86_64"
    OS_NAME="linux"
else
    echo "Unsupported operating system: $OS"
    exit 1
fi

mkdir -p "$INSTALL_DIR"
CACHE_DIR="$HOME/.$BINARY_NAME"

cleanup_cache() {
    if [ -d "$CACHE_DIR" ]; then
        rm -rf "$CACHE_DIR"/*.json
    fi
}

check_preexisting_install() {
    if [ -e "$INSTALL_DIR/$BINARY_NAME" ]; then
        echo "Found preexisting $BINARY_NAME installation: $INSTALL_DIR/$BINARY_NAME"
                echo "Overwriting the existing installation."
                cleanup_cache
    fi
}

setup_path() {
    if [[ ":$PATH:" != *":$INSTALL_DIR:"* ]]; then
        SHELL_CONFIG="$HOME/.bashrc"
        if [ -f "$HOME/.zshrc" ]; then
            SHELL_CONFIG="$HOME/.zshrc"
        fi
        echo "export PATH=\"\$PATH:$INSTALL_DIR\"" >> "$SHELL_CONFIG"
        export PATH="$PATH:$INSTALL_DIR"
    fi
}

install_binary() {
    echo "Downloading BlueArch CLI..."
    DOWNLOAD_URL="https://dist.bluearch.io/alerting-engine-api/latest/${BINARY_NAME}_${OS_NAME}_${ARCH}"
    curl -fsSL "$DOWNLOAD_URL" -o "$INSTALL_DIR/$BINARY_NAME"
    chmod +x "$INSTALL_DIR/$BINARY_NAME"
}


main() {
    echo "Installing BlueArch CLI..."
    check_preexisting_install
    cleanup_cache
    setup_path
    install_binary
    echo_ascii_art
    echo "BlueArch CLI installed successfully!"
    echo "You can now run: bluearch"
    echo "Please restart your terminal or run: source $SHELL_CONFIG"
}

main
  