#!/bin/bash

set -e

# Check for necessary tools
command -v curl >/dev/null 2>&1 || { echo >&2 "curl is required but it's not installed. Aborting."; exit 1; }
command -v tar >/dev/null 2>&1 || { echo >&2 "tar is required but it's not installed. Aborting."; exit 1; }

# Function to download and extract the file
download_and_extract() {
    local url=$1
    local file="libchdb.tar.gz"

    echo "Attempting to download $PLATFORM from $url"

    # Download the file with a retry logic
    if curl -L -o "$file" "$url"; then
        echo "Download successful."

        # Optional: Verify download integrity here, if checksums are provided

        # Untar the file
        if tar -xzf "$file"; then
            echo "Extraction successful."
            return 0
        fi
    fi
    return 1
}

# The engine this crate is developed against. Keep it on its own line and
# literal, and in step with CHDB_ENGINE_PIN in build.rs: the release check greps
# for both when it proposes a bump.
CHDB_ENGINE_PIN=v26.11.0-rc.2

# CHDB_ENGINE_VERSION overrides the pin, which is how the release check runs the
# suite against an engine this repository has not adopted yet.
LATEST_RELEASE="${CHDB_ENGINE_VERSION:-$CHDB_ENGINE_PIN}"

# Select the correct package based on OS and architecture
case "$(uname -s)" in
    Linux)
        if [[ $(uname -m) == "aarch64" ]]; then
            PLATFORM="linux-aarch64-libchdb.tar.gz"
        else
            PLATFORM="linux-x86_64-libchdb.tar.gz"
        fi
        ;;
    Darwin)
        if [[ $(uname -m) == "arm64" ]]; then
            PLATFORM="macos-arm64-libchdb.tar.gz"
        else
            PLATFORM="macos-x86_64-libchdb.tar.gz"
        fi
        ;;
    *)
        echo "Unsupported platform"
        exit 1
        ;;
esac

# One URL, and a failure is a failure. There used to be a fallback to
# releases/latest, which answered "this version could not be downloaded" by
# fetching a different version and saying nothing. That makes a build
# irreproducible for the same reason an unpinned version does, and it defeats the
# release check outright: the check would run against whatever was newest, report
# the version it was asked about as passing, and propose pinning a tag nothing
# ever built.
DOWNLOAD_URL="https://github.com/chdb-io/chdb-core/releases/download/$LATEST_RELEASE/$PLATFORM"

if ! download_and_extract "$DOWNLOAD_URL"; then
    echo "Could not download $PLATFORM for $LATEST_RELEASE. Aborting." >&2
    exit 1
fi

chmod +x libchdb.so
rm -f chdb.hpp

if [[ "$1" == "--global" ]]; then
  # If current uid is not 0, check if sudo is available and request the user to input the password
  if [[ $EUID -ne 0 ]]; then
      command -v sudo >/dev/null 2>&1 || { echo >&2 "This script requires sudo privileges but sudo is not installed. Aborting."; exit 1; }
      echo "Installation requires administrative access. You will be prompted for your password."
  fi

  # Define color messages if terminal supports them
  if [[ -t 1 ]]; then
      RED='\033[0;31m'
      GREEN='\033[0;32m'
      NC='\033[0m'  # No Color
      REDECHO() { echo -e "${RED}$@${NC}"; }
      GREENECHO() { echo -e "${GREEN}$@${NC}"; }
      ENDECHO() { echo -ne "${NC}"; }
  else
      REDECHO() { echo "$@"; }
      GREENECHO() { echo "$@"; }
      ENDECHO() { :; }
  fi

  # Use sudo if not running as root
  SUDO=''
  if [[ $EUID -ne 0 ]]; then
      SUDO='sudo'
      GREENECHO "\nYou will be asked for your sudo password to install:"
      echo "    libchdb.so to /usr/local/lib/"
      echo "    chdb.h to /usr/local/include/"
  fi

  # Make sure the library and header directory exists
  ${SUDO} mkdir -p /usr/local/lib /usr/local/include || true

  # Install the library and header file
  ${SUDO} /bin/cp libchdb.so /usr/local/lib/
  ${SUDO} /bin/cp chdb.h /usr/local/include/

  # Set execute permission for libchdb.so
  ${SUDO} chmod +x /usr/local/lib/libchdb.so

  # Update library cache (Linux specific)
  if [[ "$(uname -s)" == "Linux" ]]; then
      ${SUDO} ldconfig
  fi

  GREENECHO "Installation completed successfully." ; ENDECHO
  GREENECHO "If any error occurred, please report it to:" ; ENDECHO
  GREENECHO "    https://github.com/chdb-io/chdb/issues/new/choose" ; ENDECHO
fi
