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

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
PREFIX="${PREFIX:-/usr/local/imap}"

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

Environment:
  PREFIX    (default: /usr/local/imap)

Installs:
  - headers to: \$PREFIX/include
  - static lib to: \$PREFIX/lib/libc-client.a
  - binaries to: \$PREFIX/bin (if present)
USAGE
}

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

cd "$ROOT"

SRC_LIB="${ROOT}/c-client/c-client.a"
SRC_HDR_DIR="${ROOT}/c-client"

if [[ ! -f "$SRC_LIB" ]]; then
  echo "ERROR: $SRC_LIB not found. Build first (./scripts/build.sh)." >&2
  exit 1
fi

echo "==> Installing to PREFIX=$PREFIX"
install -d -m 0755 "$PREFIX/include" "$PREFIX/lib" "$PREFIX/bin"

echo "==> Installing headers"
install -m 0644 "$SRC_HDR_DIR"/*.h "$PREFIX/include/"

echo "==> Installing libc-client.a"
install -m 0644 "$SRC_LIB" "$PREFIX/lib/libc-client.a"

echo "==> Installing binaries (if present)"
# Common outputs after 'make bundled'
bins=(
  "$ROOT/mtest/mtest"
  "$ROOT/imapd/imapd"
  "$ROOT/ipopd/ipopd"
  "$ROOT/mailutil/mailutil"
  "$ROOT/mlock/mlock"
  "$ROOT/dmail/dmail"
  "$ROOT/tmail/tmail"
)

installed_any=0
for b in "${bins[@]}"; do
  if [[ -x "$b" ]]; then
    install -m 0755 "$b" "$PREFIX/bin/"
    echo "  installed: $(basename "$b")"
    installed_any=1
  else
    echo "  skipped:   $(basename "$b") (not found/executable)"
  fi
done

echo "==> Done."
echo "Installed:"
echo "  Headers:  $PREFIX/include/*.h"
echo "  Library:  $PREFIX/lib/libc-client.a"
if [[ "$installed_any" -eq 1 ]]; then
  echo "  Binaries: $PREFIX/bin/"
else
  echo "  Binaries: none (run ./scripts/build.sh to build bundled tools)"
fi
