#!/bin/zsh

set -euo pipefail

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

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

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 requirements-py3.txt
else
    echo "Reusing venv $VENV"
fi

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

# 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

  if [ -n "${CODE_SIGN_IDENTITY-}" ]; then
    echo "Signing app bundle"
    src/thg/contrib/sign-py2app.sh dist/${APP_NAME}.app
  fi

  toolchain/receipts/createDmg.sh
fi
