#!/bin/sh

PREFIX="/usr/local"
DEBUGDIR="dist"
WITH_BIN="zoi"

for arg in "$@"; do
  case $arg in
  --prefix=*)
    PREFIX=$(echo "$arg" | sed 's/--prefix=//')
    ;;
  --debug-dir=*)
    DEBUGDIR=$(echo "$arg" | sed 's/--debug-dir=//')
    ;;
  --with-bin=*)
    WITH_BIN=$(echo "$arg" | sed 's/--with-bin=//')
    if [ "$WITH_BIN" != "zoi" ] && [ "$WITH_BIN" != "zoi-mini" ] && [ "$WITH_BIN" != "zoid" ] && [ "$WITH_BIN" != "all" ]; then
      echo "Error: --with-bin must be 'zoi', 'zoi-mini', 'zoid', or 'all'."
      exit 1
    fi
    ;;
  *)
    echo "Unknown option: $arg"
    echo "Usage: ./configure [--prefix=/path/to/install] [--debug-dir=dist] [--with-bin=zoi|zoi-mini|zoid|all]"
    exit 1
    ;;
  esac
done

OS_NAME=$(uname -s)
ARCH_NAME=$(uname -m)

echo "Checking dependencies..."

check_cmd() {
  if ! command -v "$1" >/dev/null 2>&1; then
    echo "Error: '$1' is not installed or not in PATH."
    return 1
  fi
  return 0
}

MISSING_DEPS=0
check_cmd "cargo" || MISSING_DEPS=1
check_cmd "gcc" || check_cmd "cc" || MISSING_DEPS=1
check_cmd "pkg-config" || MISSING_DEPS=1
check_cmd "git" || MISSING_DEPS=1

if ! command -v "clang" >/dev/null 2>&1; then
  echo "Error: 'clang' is not installed. It is required for bindgen (openssl-sys, etc)."
  if [ -f /etc/fedora-release ] || [ -f /etc/redhat-release ]; then
    echo "  -> On Fedora/RHEL, run: sudo dnf install clang clang-devel"
  elif [ -f /etc/debian_version ]; then
    echo "  -> On Debian/Ubuntu, run: sudo apt-get install clang libclang-dev"
  fi
  MISSING_DEPS=1
fi

if [ $MISSING_DEPS -eq 1 ]; then
  echo ""
  echo "Some required dependencies are missing. Please install them and try again."
  exit 1
fi

case $OS_NAME in
Linux) OS_NAME="linux" ;;
Darwin) OS_NAME="macos" ;;
*NT*)
  OS_NAME="windows"
  ;;
*)
  echo "Warning: Unsupported OS '$OS_NAME' detected. The build may fail."
  ;;
esac

case $ARCH_NAME in
x86_64 | amd64) ARCH_NAME="amd64" ;;
aarch64 | arm64) ARCH_NAME="arm64" ;;
*)
  echo "Warning: Unsupported architecture '$ARCH_NAME' detected. The build may fail."
  ;;
esac

cat <<EOF >config.just
# This file is generated by ./configure. Do not edit.

# Installation prefix
PREFIX=$PREFIX

# Directory for executables (derived from PREFIX)
BINDIR=$PREFIX/bin

# Directory for debug builds
DEBUGDIR=$DEBUGDIR

# Detected OS and Architecture
OS_NAME=$OS_NAME
ARCH_NAME=$ARCH_NAME

# Binaries to build
WITH_BIN=$WITH_BIN
EOF

echo "Zoi configured successfully:"
echo "  Installation prefix:  $PREFIX"
echo "  Binary directory:     \$PREFIX/bin"
echo "  Debug directory:      $DEBUGDIR"
echo "  Operating System:     $OS_NAME"
echo "  Architecture:         $ARCH_NAME"
echo ""
echo "Now run 'just' to build and 'just install' to install."
