#!/bin/bash
#
# This script downloads and installs the mcp-bridge binary for your system.

set -e

# Define the repository URL where the binaries are stored.
REPO_URL="https://git.nixc.us/colin/mcp-bridge/raw/branch/main"
BINARY_NAME="mcp-bridge"
DEFAULT_INSTALL_DIR="/usr/local/bin"

# Parse command line arguments
while [ $# -gt 0 ]; do
  case "$1" in
    --dir=*)
      INSTALL_DIR="${1#*=}"
      shift
      ;;
    --help)
      echo "Usage: $0 [options]"
      echo "Options:"
      echo "  --dir=PATH    Install the binary to PATH (default: $DEFAULT_INSTALL_DIR)"
      echo "  --help        Show this help message"
      exit 0
      ;;
    *)
      echo "Unknown option: $1"
      echo "Run '$0 --help' for usage information."
      exit 1
      ;;
  esac
done

# Set default install directory if not specified
INSTALL_DIR="${INSTALL_DIR:-$DEFAULT_INSTALL_DIR}"

# Create the installation directory if it doesn't exist
mkdir -p "$INSTALL_DIR" 2>/dev/null || true

# Determine the operating system and architecture.
OS="$(uname -s | tr '[:upper:]' '[:lower:]')"
ARCH="$(uname -m)"

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

case "$OS" in
  linux)
    ;;
  darwin)
    ;;
  *)
    echo "Error: Unsupported OS: $OS"
    echo "Supported operating systems: linux, darwin (macOS)"
    exit 1
    ;;
esac

# Construct the download URL for the binary.
BINARY_URL="${REPO_URL}/dist/${BINARY_NAME}-${OS}-${ARCH}"
CHECKSUM_URL="${BINARY_URL}.sha256"
INSTALL_PATH="${INSTALL_DIR}/${BINARY_NAME}"

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

# Create a temporary directory for downloads
TMP_DIR=$(mktemp -d)
trap 'rm -rf "$TMP_DIR"' EXIT

# Download the binary to a temporary path.
# Use curl, and fail if the download fails.
if ! curl -sSL -f -o "${TMP_DIR}/${BINARY_NAME}" "${BINARY_URL}"; then
    echo "Error: Failed to download binary from ${BINARY_URL}"
    echo "Please check the URL and ensure that a binary for your system (${OS}/${ARCH}) exists."
    exit 1
fi

# Download the checksum if available
if curl -sSL -f -o "${TMP_DIR}/${BINARY_NAME}.sha256" "${CHECKSUM_URL}" 2>/dev/null; then
    echo "Verifying checksum..."
    
    # Extract the expected checksum
    EXPECTED_CHECKSUM=$(cat "${TMP_DIR}/${BINARY_NAME}.sha256" | awk '{print $1}')
    
    # Calculate the actual checksum
    if command -v sha256sum >/dev/null 2>&1; then
        ACTUAL_CHECKSUM=$(sha256sum "${TMP_DIR}/${BINARY_NAME}" | awk '{print $1}')
    elif command -v shasum >/dev/null 2>&1; then
        ACTUAL_CHECKSUM=$(shasum -a 256 "${TMP_DIR}/${BINARY_NAME}" | awk '{print $1}')
    else
        echo "Warning: Could not verify checksum (sha256sum/shasum not found)"
        ACTUAL_CHECKSUM=$EXPECTED_CHECKSUM  # Skip verification
    fi
    
    # Verify the checksum
    if [ "$EXPECTED_CHECKSUM" != "$ACTUAL_CHECKSUM" ]; then
        echo "Error: Checksum verification failed!"
        echo "Expected: $EXPECTED_CHECKSUM"
        echo "Actual:   $ACTUAL_CHECKSUM"
        exit 1
    fi
    
    echo "Checksum verified successfully."
fi

echo "Installing ${BINARY_NAME} to ${INSTALL_PATH}"

# Make the binary executable
chmod +x "${TMP_DIR}/${BINARY_NAME}"

# Move the binary to the installation directory.
# This may require sudo privileges if the user doesn't have write access.
if [ -w "$INSTALL_DIR" ]; then
    mv "${TMP_DIR}/${BINARY_NAME}" "$INSTALL_PATH"
else
    echo "Write access to ${INSTALL_DIR} is required."
    # Try to use sudo if available
    if command -v sudo >/dev/null 2>&1; then
        echo "Using sudo to install to ${INSTALL_PATH}"
        sudo mv "${TMP_DIR}/${BINARY_NAME}" "$INSTALL_PATH"
    else
        echo "Error: Cannot write to ${INSTALL_DIR} and sudo is not available."
        echo "Please run this script with sudo or specify a different installation directory with --dir=PATH."
        exit 1
    fi
fi

echo "${BINARY_NAME} installed successfully to ${INSTALL_PATH}!"

# Check if the installation directory is in PATH
if ! echo "$PATH" | tr ':' '\n' | grep -q "^$INSTALL_DIR$"; then
    echo ""
    echo "Warning: ${INSTALL_DIR} is not in your PATH."
    echo "You may need to add it to your PATH to run ${BINARY_NAME} without specifying the full path."
    echo ""
    echo "For bash/zsh, add the following to your ~/.bashrc or ~/.zshrc:"
    echo "  export PATH=\$PATH:${INSTALL_DIR}"
    echo ""
    echo "Then reload your shell or run: source ~/.bashrc (or ~/.zshrc)"
fi

echo ""
echo "You can now run '${BINARY_NAME}' to start the MCP bridge."
echo "Run '${BINARY_NAME} --help' for usage information."
