#!/bin/bash

set -e

if [[ $(command -v brew) == "" ]]; then
    echo "Installing (native) Homebrew..."
    /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
else
    echo "Native Homebrew has been detected, make sure it's been updated recently!"
fi
if [[ ! -x "/usr/local/bin/brew" ]] && [[ $(uname -m) == "arm64" ]]; then
    echo "Installing x86_64 Homebrew..."
    arch -x86_64 /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
fi

echo "Installing build dependencies..."
brew install python-setuptools numworks/tap/epsilon-sdk libpng gmp mpfr mpfi
if [[ $(uname -m) == "arm64" ]]; then
    arch -x86_64 /usr/local/bin/brew install libpng gmp mpfr mpfi
fi

echo "Cloning sources..."
cd /tmp
rm -rf epsilon
git clone -b version-22 --depth 1 https://github.com/parisseb/epsilon
cd epsilon
wget https://www-fourier.univ-grenoble-alpes.fr/~parisse/numworks/ext.tar.bz2
tar xfj ext.tar.bz2
wget https://www-fourier.univ-grenoble-alpes.fr/~parisse/numworks/nwsimu.tgz
tar xfz nwsimu.tgz

echo "Building..."
set +e
./mkmac

echo "Packaging"
mkdir tmp
mv output/release/simulator/macos/epsilon.app tmp
pkgbuild --install-location /Applications --identifier khicasnw.pkg.app --root tmp ~/Downloads/Khicasnw.pkg

echo "Moving things into place..."
wget https://www-fourier.univ-grenoble-alpes.fr/~parisse/khi92.tar
mv khi92.tar ~/Documents/scripts.tar
mv tmp/epsilon.app /Applications

echo "epsilon.app is now available in /Applications/"
open /Applications/epsilon.app
