#!/bin/bash
set -euo pipefail

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
APP_ROOT_DIR="$(dirname "$SCRIPT_DIR")"
ROOT_DIR="$(dirname "$(dirname "$SCRIPT_DIR")")"
. "$APP_ROOT_DIR/config.sh"

CHANNEL="beta"
BRANCH="main"
BUILD_ONLY=0
if [ "`uname`" = "Darwin" ]; then
	export SAFARI_APPEX="$ROOT_DIR/../safari-web-extension-builds/ZoteroSafariExtension.appex"
	export SAFARI_EXT_RESOURCES="$ROOT_DIR/../safari-web-extension-builds/beta/safari"
	export SAFARI_APP_EXTENSION="$ROOT_DIR/../safari-app-extension-builds/beta/ZoteroSafariExtension.appex"
	if [ ! -d "$SAFARI_APPEX" ]; then
		echo "Safari extension stub not found at $SAFARI_APPEX -- aborting" >&2
		exit 1
	fi
	if [ ! -f "$SAFARI_EXT_RESOURCES/manifest.json" ]; then
		echo "Safari web extension not found in $SAFARI_EXT_RESOURCES -- aborting" >&2
		exit 1
	fi
	if [ ! -d "$SAFARI_APP_EXTENSION" ]; then
		echo "Safari App Extension not found at $SAFARI_APP_EXTENSION -- aborting" >&2
		exit 1
	fi
fi

while getopts "b" opt; do
	case $opt in
		b)
			BUILD_ONLY=1
			;;
	esac
	shift $((OPTIND-1)); OPTIND=1
done

cd "$SCRIPT_DIR"
./check_requirements

hash=`./get_repo_branch_hash $BRANCH`
./check_app_matches_commit $hash
source_dir=`./get_commit_files $hash`
build_dir=`mktemp -d`

function cleanup {
	rm -rf "$source_dir"
	rm -rf "$build_dir"
}
trap cleanup EXIT

./prepare_build -s "$source_dir" -o "$build_dir" -c $CHANNEL -m $hash
VERSION="`cat \"$build_dir/version\"`"
./build_for_deploy -d "$build_dir" -p $BUILD_PLATFORMS -c $CHANNEL

if [ $BUILD_ONLY -eq 1 ]; then
	echo
	echo "Build only -- skipping deploy."
	echo "To deploy, run on the deploy server:"
	echo "  $DEPLOY_PATH/deploy $CHANNEL $VERSION $BUILD_PLATFORMS"
else
	ssh $DEPLOY_HOST "$DEPLOY_PATH/deploy" $CHANNEL "$VERSION" $BUILD_PLATFORMS
fi
