#!/bin/sh
set -e

# hteetp installer script
# Usage: curl -fsSL https://raw.githubusercontent.com/eastlondoner/hteetp/main/install.sh | sh

REPO="eastlondoner/hteetp"
INSTALL_DIR="${INSTALL_DIR:-/usr/local/bin}"
BINARY_NAME="hteetp"

# Detect OS and architecture
detect_platform() {
  OS=$(uname -s)
  ARCH=$(uname -m)
  
  case "$OS" in
    Darwin)
      case "$ARCH" in
        arm64|aarch64)
          PLATFORM="macos-arm64"
          ;;
        x86_64)
          PLATFORM="macos-x64"
          ;;
        *)
          echo "Unsupported architecture: $ARCH"
          exit 1
          ;;
      esac
      ;;
    Linux)
      case "$ARCH" in
        x86_64)
          PLATFORM="linux-x64"
          ;;
        aarch64|arm64)
          PLATFORM="linux-arm64"
          ;;
        *)
          echo "Unsupported architecture: $ARCH"
          exit 1
          ;;
      esac
      ;;
    *)
      echo "Unsupported OS: $OS"
      exit 1
      ;;
  esac
}

# Get latest release version
get_latest_version() {
  VERSION=$(curl -s "https://api.github.com/repos/$REPO/releases/latest" | grep '"tag_name"' | sed -E 's/.*"([^"]+)".*/\1/')
  if [ -z "$VERSION" ]; then
    echo "Failed to get latest version"
    exit 1
  fi
  echo "Latest version: $VERSION"
}

# Download and install
install() {
  DOWNLOAD_URL="https://github.com/$REPO/releases/download/$VERSION/hteetp-$PLATFORM.gz"
  TMP_GZ=$(mktemp)
  TMP_FILE=$(mktemp)
  
  echo "Downloading from: $DOWNLOAD_URL"
  curl -L -o "$TMP_GZ" "$DOWNLOAD_URL"
  
  echo "Decompressing..."
  gunzip -c "$TMP_GZ" > "$TMP_FILE"
  rm "$TMP_GZ"
  
  # Try to install to /usr/local/bin, fall back to ~/.local/bin if no sudo
  if [ -w "$INSTALL_DIR" ]; then
    mv "$TMP_FILE" "$INSTALL_DIR/$BINARY_NAME"
    chmod 755 "$INSTALL_DIR/$BINARY_NAME"
    echo "✅ Installed to $INSTALL_DIR/$BINARY_NAME"
  else
    echo "Need sudo to install to $INSTALL_DIR"
    sudo mv "$TMP_FILE" "$INSTALL_DIR/$BINARY_NAME"
    sudo chmod 755 "$INSTALL_DIR/$BINARY_NAME"
    echo "✅ Installed to $INSTALL_DIR/$BINARY_NAME"
  fi
  
  # Verify installation
  if command -v "$BINARY_NAME" >/dev/null 2>&1; then
    echo "✅ hteetp installed successfully!"
    echo ""
    echo "Run 'hteetp --help' to get started"
  else
    echo "⚠️  Installation complete, but '$BINARY_NAME' is not in PATH"
    echo "You may need to add $INSTALL_DIR to your PATH"
  fi
}

main() {
  echo "=== hteetp installer ==="
  detect_platform
  echo "Platform: $PLATFORM"
  get_latest_version
  install
}

main

