#!/bin/sh
# Install script for tunnel CLI
# Usage: curl -fsSL https://tunnel.x2s.ai/install.sh | sh
set -e

SERVER="https://dl.tunnel.x2s.ai"
BINARY="tunnel"
INSTALL_DIR="/usr/local/bin"

# Detect OS and arch
OS=$(uname -s | tr '[:upper:]' '[:lower:]')
ARCH=$(uname -m)

case "$ARCH" in
  x86_64|amd64)  ARCH="amd64" ;;
  aarch64|arm64)  ARCH="arm64" ;;
  *)              echo "Unsupported architecture: $ARCH"; exit 1 ;;
esac

case "$OS" in
  linux)  ;;
  darwin) ;;
  *)      echo "Unsupported OS: $OS"; exit 1 ;;
esac

ASSET="tunnel-${OS}-${ARCH}"
URL="${SERVER}/${ASSET}"

echo "Downloading tunnel for ${OS}/${ARCH}..."

TMP=$(mktemp)
if ! curl -fsSL -o "$TMP" "$URL" 2>/dev/null; then
  rm -f "$TMP"
  echo ""
  echo "ERROR: Download failed from $URL"
  echo ""
  echo "Manual install:"
  echo "  git clone https://github.com/bsvogler/k8s-runpod-kubelet.git"
  echo "  cd k8s-runpod-kubelet && go build -o tunnel ./cmd/tunnel-client/"
  echo "  sudo mv tunnel ${INSTALL_DIR}/"
  exit 1
fi

chmod +x "$TMP"

# Install to /usr/local/bin or ~/.local/bin
if [ -w "$INSTALL_DIR" ]; then
  mv "$TMP" "${INSTALL_DIR}/${BINARY}"
elif command -v sudo >/dev/null 2>&1; then
  sudo mv "$TMP" "${INSTALL_DIR}/${BINARY}"
else
  INSTALL_DIR="$HOME/.local/bin"
  mkdir -p "$INSTALL_DIR"
  mv "$TMP" "${INSTALL_DIR}/${BINARY}"
  echo ""
  echo "Installed to ${INSTALL_DIR}/${BINARY}"
  echo "Add to PATH: export PATH=\"\$PATH:${INSTALL_DIR}\""
fi

echo ""
echo "  tunnel installed to ${INSTALL_DIR}/${BINARY}"
echo ""
echo "  Quick start:"
echo "    tunnel up --token YOUR_API_KEY --ports 8080"
echo "    tunnel up --token YOUR_API_KEY --ports 8080 --daemon"
echo "    tunnel status"
echo "    tunnel down"
echo ""
