#!/usr/bin/env sh

# This script downloads the latest release of bladectl from GitHub and installs it to the system.
# Note: This script requires the GitHub CLI (gh) to be installed and authenticated.
set -eu


# Function to add a directory to PATH on Windows
add_to_windows_path() {
  # Adds the specified directory to the system PATH variable
  dir=$1
  PowerShell.exe -Command "& {[Environment]::SetEnvironmentVariable('PATH', [Environment]::GetEnvironmentVariable('PATH', [EnvironmentVariableTarget]::User) + ';${dir}', [EnvironmentVariableTarget]::User)}"
}


# Detect OS and Architecture
URL_PREFIX="https://kubox-public-ro.s3.ap-southeast-2.amazonaws.com/kubox_releases/latest"
OS=""
ARCH=""
BINARY_PREFIX="kubox_"
INSTALL_NAME="kubox"

case "$(uname -s)" in
  Darwin) OS="darwin" ;;
  Linux) OS="linux" ;;
  CYGWIN* | MINGW32* | MSYS* | MINGW*) OS="windows" ;;
  *)
    echo "Unsupported OS"
    exit 1
    ;;
esac

case "$(uname -m)" in
  x86_64) ARCH="amd64" ;;
  arm64) ARCH="arm64" ;;
  aarch64) ARCH="arm64" ;; # Some systems report arm64 as aarch64
  *)
    echo "Unsupported architecture"
    exit 1
    ;;
esac

BINARY_NAME="${BINARY_PREFIX}${OS}_${ARCH}"
echo "Detected platform: $OS, architecture: $ARCH"
echo "Downloading $BINARY_NAME from the latest release..."

URL="$URL_PREFIX/$BINARY_NAME"
echo "Downloading from $URL"
curl --progress-bar -L "$URL" -o "$BINARY_NAME"

echo "Download successful."
mv "$BINARY_NAME" "$INSTALL_NAME"
if [ "$OS" != "windows" ]; then
chmod +x "$INSTALL_NAME"
INSTALL_DIR="/usr/local/bin"
if [ -d "$INSTALL_DIR" ]; then
    if [ -w "$INSTALL_DIR" ]; then
    mv "$INSTALL_NAME" "$INSTALL_DIR/$INSTALL_NAME"
    echo "Installed $INSTALL_NAME to $INSTALL_DIR"
    else
    echo "sudo is required to move $INSTALL_NAME to $INSTALL_DIR"
    sudo mv "$INSTALL_NAME" "$INSTALL_DIR/$INSTALL_NAME"
    echo "Installed $INSTALL_NAME to $INSTALL_DIR"
    fi
else
    echo "Installation directory $INSTALL_DIR does not exist. $INSTALL_NAME was not moved."
fi
else
# Windows-specific installation
INSTALL_DIR="$HOME/bin"
if [ ! -d "$INSTALL_DIR" ]; then
    mkdir -p "$INSTALL_DIR"
fi
mv "$INSTALL_NAME" "$INSTALL_DIR/$INSTALL_NAME"
add_to_windows_path "$INSTALL_DIR"
echo "Installed $INSTALL_NAME to $INSTALL_DIR and attempted to add it to PATH. Please restart your terminal."
fi
echo "'kubox' is installed successfully."
echo "Visit https://docs.kubox.ai for more information."