#!/bin/sh
ZSIGN=`which zsign`
CURDIR=`dirname "$(readlink -f "$0")"`

if [ -z "$ZSIGN" ]; then
    if [ -x "zsign" ]; then
        ZSIGN="./zsign"
    elif [ -x "$CURDIR/zsign" ]; then
        ZSIGN="$CURDIR/zsign"
    else
        echo "This script requires 'zsign' to be in your path. If zsign is not yet installed, you can download it from: "
        echo "    https://github.com/zhlynn/zsign"
        echo "If building on MacOS, a manual fix is needed before compiling. See:"
        echo "    https://githubmemory.com/repo/zhlynn/zsign/issues/208"
        echo "or you may use the helper script to build it:"
        echo "    build_zsign.sh"
        exit 1
    fi
fi

if [ -z "$CFA_PROVISIONING_PROFILE" ]; then
    echo ""
    echo "Set 'CFA_PROVISIONING_PROFILE' to a valid .mobileprovision file and run again"
    echo ""
    echo "(Consider ~/Library/MobileDevice/Provisioning\ Profiles/... on your Xcode development machine)"
    exit 1
fi

if [ -z "$CFA_PROVISIONING_CERT" ]; then
    echo ""
    echo "Set 'CFA_PROVISIONING_CERT' to a valid .p12 certificate file"
    echo ""
    echo "(See: https://www.ssl.com/how-to/export-a-pkcs-12-pfx-file-from-keychain-access-on-macos/ )"
    exit 1
fi

for app in "$@"
do
    $ZSIGN -m "$CFA_PROVISIONING_PROFILE" -k "$CFA_PROVISIONING_CERT" $app 
    #echo "\"$ZSIGN\" -m \"$CFA_PROVISIONING_PROFILE\" -k \"$CFA_PROVISIONING_CERT\" $app "
done
