#!/bin/bash

BIN=$PREFIX/bin
KEYCHAIN=/Users/builder/Library/Keychains/anaconda-installer.keychain

if [[ $(uname) == Darwin ]]; then
    mv anaconda_navigator/app/Navigator.app $PREFIX/navigatorapp
    sed -i '' 's/0.01/$PKG_VERSION/' $PREFIX/navigatorapp/Contents/Info.plist
    find $PREFIX/navigatorapp -name '__init__.py' | xargs rm

    # MacOS is now very sensitive about permissions
    # Permissions for running apps are determined based on the top level
    # executable that launches the app. We can't sign /bin/sh
    # so we need to include a binary signed by us within our app
    cp $PREFIX/bin/python $PREFIX/navigatorapp/Contents/MacOS
    AE=$PREFIX/navigatorapp/Contents/MacOS/run.py
    cat <<EOF >$AE
#!${PREFIX}/Anaconda-Navigator.app/Contents/MacOS/python
from subprocess import call

call(["$PREFIX/bin/anaconda-navigator"])
EOF
    chmod +x $AE

    cp -r $PREFIX/navigatorapp $PREFIX/Anaconda-Navigator.app
    rm -rf $PREFIX/navigatorapp
    # sign the python executable and our python script - this also results in the app itself being signed
    find $PREFIX/Anaconda-Navigator.app/ -name 'python' | xargs codesign --verbose -s 'Apple Development: AD Team' --keychain $KEYCHAIN
    codesign -s 'Apple Development: AD Team' $PREFIX/Anaconda-Navigator.app --verbose --keychain $KEYCHAIN

    # Check that the app is signed
    codesign -d $PREFIX/Anaconda-Navigator.app -vvv

    POST_LINK=$BIN/.anaconda-navigator-post-link.sh
    PRE_UNLINK=$BIN/.anaconda-navigator-pre-unlink.sh
    cp $RECIPE_DIR/osx-post.sh $POST_LINK
    cp $RECIPE_DIR/osx-pre.sh $PRE_UNLINK
    chmod +x $POST_LINK $PRE_UNLINK

else # not Darwin
    rm -rf anaconda_navigator/app/Navigator.app
fi

$PYTHON setup.py install --old-and-unmanageable
