#!/bin/bash
#
# Builds Zotero and uploads to S3 and deploy server, but does not make the build live.
# To make the build live, run the deploy script on the deploy server (or via SSH).
#
set -euo pipefail

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

function usage {
	cat >&2 <<DONE
Usage: $0 -d SOURCE_DIR -c CHANNEL -p PLATFORMS
 -d SOURCE_DIR       Source directory to build from
 -c CHANNEL          Release channel ('release', 'beta', 'dev')
 -p PLATFORMS        Platforms to build (m=Mac, w=Windows, l=Linux)
 -i INCREMENTALS     Number of incremental builds to create
DONE
	exit 1
}


SOURCE_DIR=""
CHANNEL=""
PLATFORMS=""
while getopts "d:c:p:i:" opt; do
	case $opt in
		d)
			SOURCE_DIR="$OPTARG"
			if [ ! -d "$SOURCE_DIR" ]; then
				echo "$SOURCE_DIR not found"
				exit 1
			fi
			;;
		c)
			CHANNEL="$OPTARG"
			;;
		p)
			PLATFORMS="$OPTARG"
			;;
		i)
			NUM_INCREMENTALS="$OPTARG"
			;;
		*)
			usage
			;;
	esac
	shift $((OPTIND-1)); OPTIND=1
done

if [[ -z "$SOURCE_DIR" ]] || [[ -z "$CHANNEL" ]] || [[ -z "$PLATFORMS" ]]; then
	usage
fi

"$SCRIPT_DIR"/check_requirements

VERSION="`cat \"$SOURCE_DIR\"/version`"
if [ -z "$VERSION" ]; then
	echo "Error getting version from $SOURCE_DIR/version"
	exit 1
fi

# Enforce signing unless a test build or macOS, which doesn't start otherwise
if [[ "$CHANNEL" != "test" || $PLATFORMS = "m" ]]; then
	SIGN="-e"
else
	SIGN=""
fi

# Build Zotero
"$ROOT_DIR/build.sh" -d "$SOURCE_DIR" -p $PLATFORMS -c $CHANNEL $SIGN

BUILD_ID=`cat "$DIST_DIR/build_id"`
if [ -z "$BUILD_ID" ]; then
	echo "Error getting build id"
	exit 1
fi

TEMP_DIR=`mktemp -d`
# Clean up on exit
function cleanup {
	rm -rf "$TEMP_DIR"
}
trap cleanup EXIT

# Build full update
"$ROOT_DIR/update-packaging/build_autoupdate.sh" -f -c $CHANNEL -p $PLATFORMS -l $VERSION

# Build incremental updates for each platform
for i in `seq 0 1 $((${#PLATFORMS}-1))`
do
	case ${PLATFORMS:i:1} in
		m)
			platform=mac
			platform_name=Mac
			;;
		w)
			platform=win
			platform_name=Windows
			;;
		l)
			platform=linux
			platform_name=Linux
			;;
		*)
			echo "$0: Invalid platform option ${PLATFORMS:i:1}"
			usage
			;;
	esac

	echo
	echo "Getting $platform_name incrementals"
	INCREMENTALS="`\"$SCRIPT_DIR/manage_incrementals\" -c $CHANNEL -p ${PLATFORMS:i:1} -n $NUM_INCREMENTALS`"

	# Fetch pinned incrementals from deploy server and merge
	PINNED_FILE="$DEPLOY_PATH/manifests/$CHANNEL/pinned-incrementals-$platform"
	PINNED=""
	if ssh $DEPLOY_HOST "test -f $PINNED_FILE"; then
		PINNED="`ssh $DEPLOY_HOST cat $PINNED_FILE`"
	fi

	# Combine and deduplicate
	INCREMENTALS="`echo -e "$INCREMENTALS\n$PINNED" | sort -u | grep -v '^$' || true`"
	echo "$INCREMENTALS"
	echo

	if [ -n "$INCREMENTALS" ]; then
		for from in $INCREMENTALS; do
			echo "Building incremental update for $platform_name from $from to $VERSION"
			"$ROOT_DIR/update-packaging/build_autoupdate.sh" -i "$from" -c "$CHANNEL" -p ${PLATFORMS:i:1} -l $VERSION
			echo
		done
	fi
done

# Upload builds to S3
"$SCRIPT_DIR/upload_builds" $CHANNEL $VERSION

# Upload file lists and build info for each platform
channel_deploy_path="$DEPLOY_PATH/manifests/$CHANNEL"
mkdir "$TEMP_DIR/version_info"
chmod g+ws "$TEMP_DIR/version_info"
cp "$DIST_DIR"/files-* "$TEMP_DIR/version_info"
chmod g+w "$TEMP_DIR"/version_info/files-*
# Generate build-{os}.json for each platform
SHORT_VERSION=$(echo "$VERSION" | grep -oE '^[0-9]+\.[0-9]+')
DETAILS_URL="https://www.zotero.org/support/${SHORT_VERSION}_changelog"
for i in `seq 0 1 $((${#PLATFORMS}-1))`
do
	case ${PLATFORMS:i:1} in
		m) os_name="mac" ;;
		w) os_name="win" ;;
		l) os_name="linux" ;;
	esac
	printf '{\n  "buildID": "%s",\n  "detailsURL": "%s"\n}\n' "$BUILD_ID" "$DETAILS_URL" \
		> "$TEMP_DIR/version_info/build-${os_name}.json"
	chmod g+w "$TEMP_DIR/version_info/build-${os_name}.json"
done
rsync -rv "$TEMP_DIR/version_info/" $DEPLOY_HOST:"$channel_deploy_path/$VERSION/"

rm -rf "$STAGE_DIR"/*

echo
echo "Build $VERSION uploaded successfully."
echo "To deploy, run on the deploy server:"
echo "  ./deploy $CHANNEL $VERSION $PLATFORMS"
