#!/usr/bin/env bash
set -euo pipefail

# Configuration --------------------------------------------------------------
S3_BUCKET="rootaccess-hideout-prod-release"
REGION="us-east-1"
BASE_URL="https://${S3_BUCKET}.s3.${REGION}.amazonaws.com"
CHANNEL_PATH="latest"

if [[ $# -ge 1 && -n "$1" ]]; then
  VERSION="$1"
  CHANNEL_PATH="releases/v${VERSION}"
fi

ARCHIVE_DIR="macos"
BINARY_NAME="seb-darwin-arm64"
INSTALL_DIR="${HOME}/.local/bin"
DEST_PATH="${INSTALL_DIR}/seb"

# Download -------------------------------------------------------------------
DOWNLOAD_URL="${BASE_URL}/${CHANNEL_PATH}/${ARCHIVE_DIR}/${BINARY_NAME}"
TMP_FILE="$(mktemp)"

echo "Downloading SEB CLI from ${DOWNLOAD_URL}"
curl -fL "${DOWNLOAD_URL}" -o "${TMP_FILE}"

# Install --------------------------------------------------------------------
chmod +x "${TMP_FILE}"

mkdir -p "${INSTALL_DIR}"
if [[ -f "${DEST_PATH}" ]]; then
  mv "${TMP_FILE}" "${DEST_PATH}"
  echo "\033[1;33mSEB CLI has been updated at ${DEST_PATH}\033[0m"
else
  mv "${TMP_FILE}" "${DEST_PATH}"
  echo "\033[1;32mSEB CLI installed at ${DEST_PATH}\033[0m"
fi

# Finish ---------------------------------------------------------------------
echo "\033[1;36mTo verify the installation, run: seb --version\033[0m"
echo "\033[1;36mFor more information, visit: https://rootaccess.ai/docs/hideout-cli\033[0m"
echo "\033[1;36mTo login or create an account, run seb auth login\033[0m"
echo "\033[1;36mTo buy a subscription, run seb subscription buy\033[0m"