#!/bin/zsh

set -euo pipefail

DEFAULT_QT_MAJOR="5"

# Default to Qt6 on arm64 because Qt5 isn't supported there and it's unclear
# if/how to support cross compiling without Rosetta.
if [[ `arch` == arm64 ]]; then
    DEFAULT_QT_MAJOR="6"
fi

QT_MAJOR="${QT_MAJOR:-${DEFAULT_QT_MAJOR}}"

case ${QT_MAJOR} in
"5"|"6")
    ;;
*)
    echo "Only '5' or '6' is supported for QT_MAJOR: ${QT_MAJOR}"
    exit 1
    ;;
esac


export APP_NAME="TortoiseHg"
export QT_VERSION="qt${QT_MAJOR}"

PYTHON=${PYTHON:-python3}
HERE="$(hg root)/contrib/packaging/macos"
PYVERSION=$(${PYTHON} -c "import sys; print('%d.%d' % sys.version_info[:2])")
VENV="$(hg root)/build/venv-${QT_VERSION}-py${PYVERSION}"

if [[ ! -e $VENV ]]; then
    echo "Creating venv $VENV"
    ${PYTHON} -m venv --copies "${VENV}"
    ${VENV}/bin/pip --disable-pip-version-check install -U  'pip>=24'
    ${VENV}/bin/pip --disable-pip-version-check install -U  wheel==0.37.0
    ${VENV}/bin/pip --disable-pip-version-check install -r "${HERE}/requirements-pyqt${QT_MAJOR}.txt"
else
    echo "Reusing venv $VENV"
fi

export PYTHON="${VENV}/bin/python3"

cd "${HERE}"

# build mercurial + tortoisehg
${VENV}/bin/pip install --force-reinstall src/hg
toolchain/receipts/tortoisehg.sh

# CFVersion is always x.y.z format.  The plain version will have changeset info
# in non-tagged builds.
export THG_CFVERSION=$($PYTHON -c 'from tortoisehg.util import version; print(version.package_version())')
export THG_VERSION=$($PYTHON -c 'from tortoisehg.util import version; print(version.version())')

rm -rf dist/TortoiseHg.app build

# create application package
${PYTHON} setup.py --graph --xref


if [ -d dist/${APP_NAME}.app ]; then
    rm -rf build

    APP="dist/${APP_NAME}.app"

    rm "${APP}/Contents/Resources/lib/python${PYVERSION}/PyQt${QT_MAJOR}/"*.pyi
    rm -r "${APP}/Contents/Resources/lib/python${PYVERSION}/PyQt${QT_MAJOR}/Qt${QT_MAJOR}/qml"

    # Trim down to plugins bundled with the py2 app
    for f in "${APP}/Contents/Resources/lib/python${PYVERSION}/PyQt${QT_MAJOR}/Qt${QT_MAJOR}/plugins/"*; do
        case "${f##*/}" in
        iconengines | imageformats | platforms | printsupport)
            continue
            ;;
        esac

        rm -r "${f}"
    done

    # py2 app packages these *.framework bundles:
    #   Python, QtCore, QtGui, QtMacExtras, QtNetwork, QtPrintSupport, QtSvg, QtWidgets
    # For some reason, libqcocoa.dylib links against the QtDBus framework, and will crash
    # the app on launch if not present.  QtMacExtras.framework is needed to load some
    # icons on launch.

    for f in "${APP}/Contents/Resources/lib/python${PYVERSION}/PyQt${QT_MAJOR}/Qt${QT_MAJOR}/lib/"*.framework; do
        framework="${f##*/}"
        base="${framework%.*}"

        case "${base}" in
        QtDBus | QtCore | QtGui | QtMacExtras | QtNetwork | QtPrintSupport | QtSvg | QtWidgets)
            continue
            ;;
        esac

        echo "Deleting ${base} components"

        rm -f  "${APP}/Contents/Resources/lib/python${PYVERSION}/PyQt${QT_MAJOR}/${base}.abi3.so"
        rm -rf "${APP}/Contents/Resources/lib/python${PYVERSION}/PyQt${QT_MAJOR}/bindings/${base}"
        rm -r "${f}"
    done

    # Qt5 doesn't support ARM64, so strip the image to force the app to run
    # under Rosetta.
    if [ "${QT_VERSION}" = "qt5" ]; then
        xcrun lipo -thin x86_64 -o "${APP}/Contents/MacOS/TortoiseHg" "${APP}/Contents/MacOS/TortoiseHg"
    fi

    if [ -z "${CODE_SIGN_IDENTITY-}" ]; then
        # These ad hoc signing parameters are copied from py2app/util._dosign()
        CODE_SIGN_IDENTITY="-"
        OTHER_CODE_SIGN_FLAGS="--preserve-metadata=identifier,entitlements,flags,runtime"
    fi

    # Always force the signature, because we're replacing the existing one.
    echo "Signing app bundle"
    echo "codesign -s \"${CODE_SIGN_IDENTITY}\" ${OTHER_CODE_SIGN_FLAGS} --force"

    ${PYTHON} print_platform_files.py dist/${APP_NAME}.app \
        | xargs codesign -s "${CODE_SIGN_IDENTITY}" ${OTHER_CODE_SIGN_FLAGS} --force

    # Validate that everything was signed properly, or downloaded files refuse
    # to run.  It seems that `spctl -a *.app` always fails with ad hoc signing.
    codesign -vv dist/${APP_NAME}.app

    toolchain/receipts/createDmg.sh
fi
