#!/bin/zsh

set -euo pipefail

export APP_NAME="TortoiseHg"
export QT_VERSION="qt5"

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

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

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

cd "${HERE}"

# build mercurial + tortoisehg
toolchain/receipts/mercurial.sh
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}/PyQt5/"*.pyi
    rm -r "${APP}/Contents/Resources/lib/python${PYVERSION}/PyQt5/Qt5/qml"

    # Trim down to plugins bundled with the py2 app
    for f in "${APP}/Contents/Resources/lib/python${PYVERSION}/PyQt5/Qt5/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}/PyQt5/Qt5/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}/PyQt5/${base}.abi3.so"
        rm -rf "${APP}/Contents/Resources/lib/python${PYVERSION}/PyQt5/bindings/${base}"
        rm -r "${f}"
    done

    # Qt5 doesn't support ARM64, so strip the image to force the app to run
    # under Rosetta.
    xcrun lipo -thin x86_64 -o "${APP}/Contents/MacOS/TortoiseHg" "${APP}/Contents/MacOS/TortoiseHg"

    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
