#!/bin/bash

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

# Map the architecture name
if [ "$ARCH" = "x86_64" ]; then
  ARCH="amd64"
elif [ "$ARCH" = "aarch64" ]; then
  ARCH="arm64"
fi

BINARY_NAME="xtp-$OS-$ARCH"
DOWNLOAD_URL="https://static.dylibso.com/cli/bin/$BINARY_NAME"

# Function to check if a directory is in PATH and writable
is_valid_install_dir() {
  [[ ":$PATH:" == *":$1:"* ]] && [ -w "$1" ]
}

# Check for common user-writable directories in PATH
for dir in "$HOME/bin" "$HOME/.local/bin" "$HOME/.bin"; do
  if is_valid_install_dir "$dir"; then
    INSTALL_DIR="$dir"
    break
  fi
done

# If no user-writable directory found, use system directory
if [ -z "$INSTALL_DIR" ]; then
  INSTALL_DIR="/usr/local/bin"
  USE_SUDO=1
fi

# Perform installation

TARGET="$INSTALL_DIR/xtp"
echo "Downloading from: $DOWNLOAD_URL"

if curl -fsSL --output /tmp/xtp "$DOWNLOAD_URL"; then
  if [ "$USE_SUDO" = "1" ]; then
    echo "No user-writable bin directory found in PATH. Using sudo to install in $INSTALL_DIR"
    sudo cp /tmp/xtp "$TARGET"
    rm /tmp/xtp
    sudo chmod +x "$TARGET"
  else
    cp /tmp/xtp "$TARGET"
    rm /tmp/xtp
    chmod +x "$TARGET"
  fi
  echo "Successfully installed xtp to $TARGET"
else
  echo "Failed to download or install xtp. Curl exit code: $?"
  exit
fi

# Warn the user if the chosen path is not in the path
if [[ ":$PATH:" != *":$INSTALL_DIR:"* ]]; then
  echo "Note: $INSTALL_DIR is not in your PATH. You may need to add it to your PATH or use the full path to run xtp."
fi

echo "Installation complete. Try to run 'xtp --version' to ensure it was correctly installed."
