#!/usr/bin/env bash
# Install the ISOLATED Qt 5.14.2 toolchain + matching Qt Creator into .qt514/
# directly on the host, using a local venv for aqtinstall. The host already
# has the right toolchain (gcc 13.3, cmake 3.28); this just fetches files
# into the repo. No container involved (students are mostly on Windows).
#
#   Usage: tools/install_qt_host.sh
# Verified: a binary built against .qt514/ links ONLY to .qt514/ (ldd shows 0
# system-Qt refs) and runs on the host with tools/run_qt.sh.
set -euo pipefail
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
VENV="$REPO_ROOT/.venv-aqt"
QT_VERSION="5.14.2"
CREATOR_VERSION="4.11.0"
CREATOR_DIR="$REPO_ROOT/.qt514/Tools/QtCreator"
CREATOR_URL="https://download.qt.io/archive/qtcreator/${CREATOR_VERSION%.*}/${CREATOR_VERSION}/qt-creator-opensource-linux-x86_64-${CREATOR_VERSION}.run"

if [ ! -x "$VENV/bin/aqt" ]; then
    echo ">> Creating local venv with aqtinstall at $VENV ..."
    python3 -m venv "$VENV" --system-site-packages
    "$VENV/bin/pip" install --quiet aqtinstall
fi
"$VENV/bin/pip" show py7zr >/dev/null 2>&1 || "$VENV/bin/pip" install --quiet py7zr

echo ">> Installing Qt ${QT_VERSION} gcc_64 into $REPO_ROOT/.qt514/ ..."
"$VENV/bin/aqt" install-qt linux desktop "${QT_VERSION}" gcc_64 -O "$REPO_ROOT/.qt514"

QT_ROOT="$REPO_ROOT/.qt514/${QT_VERSION}/gcc_64"
echo ">> Verify:"
"$QT_ROOT/bin/qmake" -query QT_VERSION
echo ">> Qt installed at: $QT_ROOT"

# Qt Creator ${CREATOR_VERSION} (period-matched to Qt ${QT_VERSION}). The official
# .run installer for this vintage hard-gates its wizard behind a mandatory Qt
# account login with no Skip option, so we pull the .run and lift its embedded
# payload directly instead of driving the GUI. See tools/extract_qtcreator_payload.py.
if [ -x "$CREATOR_DIR/bin/qtcreator" ]; then
    echo ">> Qt Creator already installed at $CREATOR_DIR, skipping."
else
    echo ">> Downloading Qt Creator ${CREATOR_VERSION} .run installer ..."
    CREATOR_RUN="$(mktemp -t qtcreator-XXXXXX.run)"
    trap 'rm -f "$CREATOR_RUN"' EXIT
    curl -sL -o "$CREATOR_RUN" "$CREATOR_URL"
    echo ">> Extracting Qt Creator payload (bypassing account-gated GUI) ..."
    "$VENV/bin/python3" "$REPO_ROOT/tools/extract_qtcreator_payload.py" "$CREATOR_RUN" "$CREATOR_DIR"
    rm -f "$CREATOR_RUN"
    trap - EXIT
fi
echo ">> Qt Creator installed at: $CREATOR_DIR"
"$CREATOR_DIR/bin/qtcreator" -version 2>&1 | grep "^Qt Creator" || true

echo ">> Build on host:    cmake -S . -B build -G Ninja -DBUILD_QT_PART=ON -DCMAKE_PREFIX_PATH='$QT_ROOT' && cmake --build build"
echo ">> Run Qt targets:   tools/run_qt.sh <target>"
echo ">> Open Qt Creator:  tools/run_qtcreator.sh"
