#!/usr/bin/env sh
set -eu

INSTALL_DIR="${MOSAIC_INSTALL_DIR:-$HOME/.local/bin}"
BIN_NAME="${MOSAIC_BIN_NAME:-mosaic}"
MOSAIC_VERSION="0.0.17"
CURRENT_BIN="$INSTALL_DIR/$BIN_NAME"

use_color() {
  [ -t 1 ] && [ "${NO_COLOR:-0}" != "1" ]
}

paint() {
  if use_color; then
    printf '\033[%sm%s\033[0m\n' "$1" "$2"
  else
    printf '%s\n' "$2"
  fi
}

banner() {
  paint '38;5;180' 'Mosaic CLI installer'
  paint '38;5;186' "Version: $MOSAIC_VERSION"
}

info() {
  paint '38;5;110' "$1"
}

success() {
  paint '38;5;151' "$1"
}

warn() {
  paint '38;5;217' "$1"
}

banner
DOWNLOAD_URL="https://mosaic.methil.group/downloads/mosaic-linux-amd64"
OS="$(uname -s)"
ARCH="$(uname -m)"

if [ "$OS" != "Linux" ] || { [ "$ARCH" != "x86_64" ] && [ "$ARCH" != "amd64" ]; }; then
  warn "Mosaic installer currently ships linux/amd64 only."
  exit 1
fi

info "Target binary: $BIN_NAME"
info "Download: $DOWNLOAD_URL"

if [ -x "$CURRENT_BIN" ]; then
  INSTALLED_VERSION="$("$CURRENT_BIN" --version 2>/dev/null | awk 'NR == 1 { print $3 }')"
  if [ -n "$INSTALLED_VERSION" ]; then
    warn "Mosaic is already installed at $CURRENT_BIN"
    info "Installed version: $INSTALLED_VERSION"
  else
    warn "Mosaic is already installed at $CURRENT_BIN"
  fi
  warn "A reinstall will replace the existing binary with version $MOSAIC_VERSION"
  if [ -t 0 ] && [ -t 1 ] && [ "${MOSAIC_FORCE:-0}" != "1" ]; then
    printf "Reinstall Mosaic CLI version %s? [y/N] " "$MOSAIC_VERSION"
    read answer
    case "$answer" in
      y|Y|yes|YES)
        ;;
      *)
        echo "Cancelled."
        exit 0
        ;;
    esac
  fi
fi

mkdir -p "$INSTALL_DIR"
tmp="$(mktemp)"
trap 'rm -f "$tmp"' EXIT

info "Installing Mosaic CLI version $MOSAIC_VERSION..."
curl -fsSL "$DOWNLOAD_URL" -o "$tmp"
chmod +x "$tmp"
mv "$tmp" "$INSTALL_DIR/$BIN_NAME"

success "Mosaic CLI installed to $INSTALL_DIR/$BIN_NAME"
success "Installed version: $MOSAIC_VERSION"
info "Run: $BIN_NAME --workspace ."
