#!/usr/bin/env sh
set -eu

if command -v qmake6 >/dev/null 2>&1; then
  QMAKE=qmake6
elif command -v qmake >/dev/null 2>&1 && qmake -query QT_VERSION | grep -q '^6\.'; then
  QMAKE=qmake
else
  echo "A Qt 6 qmake (qmake6) is required to install QtKeychain." >&2
  exit 1
fi

QT_PREFIX="${1:-$("$QMAKE" -query QT_INSTALL_PREFIX)}"
VERSION="${QTKEYCHAIN_VERSION:-0.15.0}"
SRC="${TMPDIR:-/tmp}/qtkeychain-src-$$"
BUILD="${TMPDIR:-/tmp}/qtkeychain-build-$$"

cleanup() {
  rm -rf -- "$SRC" "$BUILD"
}
trap cleanup EXIT HUP INT TERM

git clone --depth 1 --branch "$VERSION" \
  https://github.com/frankosterfeld/qtkeychain.git "$SRC"

if [ "$(uname -s)" = Darwin ]; then
  CXX_COMPILER="${CXX:-$(command -v clang++ || command -v c++)}"
else
  # The official Qt 6 gcc_64 build and Omairc itself are compiled with GCC, so
  # QtKeychain has to match. CMake would otherwise take /usr/bin/c++, which on
  # Ubuntu 24.04 is Clang and selects a GCC 14 toolchain that build-essential
  # does not install, leaving the link without -lstdc++.
  CXX_COMPILER="${CXX:-g++}"
fi
if [ -z "$CXX_COMPILER" ]; then
  echo "A C++ compiler is required to build QtKeychain." >&2
  exit 1
fi

if command -v ninja >/dev/null 2>&1; then
  CMAKE_GENERATOR=Ninja
else
  CMAKE_GENERATOR="Unix Makefiles"
fi

cmake -S "$SRC" -B "$BUILD" -G "$CMAKE_GENERATOR" \
  -DCMAKE_BUILD_TYPE=Release \
  -DCMAKE_CXX_COMPILER="$CXX_COMPILER" \
  -DCMAKE_PREFIX_PATH="$QT_PREFIX" \
  -DCMAKE_INSTALL_PREFIX="$QT_PREFIX" \
  -DBUILD_WITH_QT6=ON \
  -DBUILD_TRANSLATIONS=OFF \
  -DBUILD_TEST_APPLICATION=OFF
cmake --build "$BUILD"
cmake --install "$BUILD"

PRI="$QT_PREFIX/mkspecs/modules/qt_Qt6Keychain.pri"
if [ ! -f "$PRI" ]; then
  PRI="$QT_PREFIX/lib/qt6/mkspecs/modules/qt_Qt6Keychain.pri"
fi
if [ ! -f "$PRI" ]; then
  PRI="$("$QMAKE" -query QT_INSTALL_ARCHDATA)/mkspecs/modules/qt_Qt6Keychain.pri"
fi
if [ ! -f "$PRI" ]; then
  echo "QtKeychain installed but qt_Qt6Keychain.pri is missing under $QT_PREFIX." >&2
  exit 1
fi
