#!/usr/bin/env bash
set -e

INSTALL_DIR="/opt/kvx"
BIN_LINK="/usr/local/bin/kvx"
TMP_DIR="$(mktemp -d)"
ARCHIVE_URL="https://sdk.kuvixos.com.tr/downloads/kvx-sdk-linux.tar.gz"

cleanup() {
  rm -rf "$TMP_DIR"
}
trap cleanup EXIT

echo "[kvx] KuvixOS SDK installer"

# uninstall desteği
if [ "${1:-}" = "--uninstall" ]; then
  echo "[kvx] uninstalling..."
  sudo rm -f "$BIN_LINK"
  sudo rm -rf "$INSTALL_DIR"
  echo "[kvx] uninstalled"
  exit 0
fi

# curl var mı kontrol
if ! command -v curl >/dev/null 2>&1; then
  echo "[kvx] error: curl not found"
  exit 1
fi

# g++ kontrol (çok önemli)
if ! command -v g++ >/dev/null 2>&1; then
  echo "[kvx] warning: g++ not found"
  echo "[kvx] install with: sudo dnf install gcc-c++"
fi

echo "[kvx] downloading SDK..."
curl -fsSL "$ARCHIVE_URL" -o "$TMP_DIR/kvx.tar.gz"

echo "[kvx] installing to $INSTALL_DIR ..."
sudo rm -rf "$INSTALL_DIR"
sudo mkdir -p "$INSTALL_DIR"

sudo tar -xzf "$TMP_DIR/kvx.tar.gz" -C "$INSTALL_DIR"

# Arşiv kök klasörü
SDK_ROOT="$INSTALL_DIR/kvx-sdk-linux"

echo "[kvx] linking binary..."
sudo chmod +x "$SDK_ROOT/kvx"
sudo ln -sf "$SDK_ROOT/kvx" "$BIN_LINK"

echo
echo "[kvx] install complete ✔"
echo
echo "Try:"
echo "  kvx init hello"
echo "  cd hello"
echo "  kvx build"
