#!/usr/bin/env bash
set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"

SSLTYPE="${SSLTYPE:-unix.nopwd}"   # recommended for RFC 3501 compliance
TARGET="${TARGET:-lnp}"            # what you used successfully
CLEAN="${CLEAN:-0}"                # set to 1 for a clean build

usage() {
  cat <<USAGE
Usage: $0

Build UW-IMAP in a deterministic, legacy-compatible order.

Environment:
  SSLTYPE   (default: unix.nopwd)
  TARGET    (default: lnp)
  CLEAN     (default: 0)  set to 1 to remove build artifacts before building

Examples:
  $0
  CLEAN=1 $0
  SSLTYPE=unix.nopwd TARGET=lnp CLEAN=1 $0
USAGE
}

if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then
  usage
  exit 0
fi

cd "$ROOT"

if [[ -d patches ]]; then
  echo "Hint: run ./scripts/apply-patches.sh before building if needed."
fi

if [[ "$CLEAN" == "1" ]]; then
  echo "==> Cleaning previous build artifacts"
  make clean || true

  # Remove common UW-IMAP build byproducts/symlink trees that can break rebuilds
  rm -f OSTYPE CFLAGS CCTYPE LDFLAGS OSCFLAGS ARCHIVE SPECIALS an 2>/dev/null || true
  rm -rf c-client mtest ipopd imapd mailutil mlock dmail tmail rebuild 2>/dev/null || true
fi

# Ensure tools/an exists and is executable (should be part of the repo)
if [[ ! -f tools/an ]]; then
  echo "ERROR: tools/an not found. Repository checkout seems incomplete." >&2
  exit 1
fi
chmod +x tools/an 2>/dev/null || true

echo "==> Step 1/3: Prepare symlinks (make an)"
# This creates the symlink layout expected by the rest of the build (c-client/, mtest/, ...)
make an

echo "==> Step 2/3: Build core (make ${TARGET} SSLTYPE=${SSLTYPE})"
# IMPORTANT: do NOT use -j here; UW-IMAP's legacy build is not reliably parallel-safe.
make "${TARGET}" "SSLTYPE=${SSLTYPE}" "EXTRACFLAGS=-I/usr/include/openssl"

echo "==> Step 3/3: Build bundled tools (make bundled)"
# Bundled tools depend on generated headers like c-client/osdep.h.
#make bundled || true
make bundled

echo "Build done."
echo "Artifacts:"
echo "  c-client/c-client.a: $(test -f c-client/c-client.a && echo OK || echo MISSING)"
echo "  c-client/osdep.h:    $(test -f c-client/osdep.h && echo OK || echo MISSING)"
