#!/bin/sh

# Copyright 2015-2023 Rivoreo

# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:

# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE
# FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
# CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

JDK_HOME=/opt/jdk1.7.0_80
if [ $# != 1 ]; then
	printf "Usage: %s <modid>\\n" "$0" 1>&2
	exit 255
fi
set -e
[ -d build/fml7/log4jsubstitution ] || mkdir -p build/fml7/log4jsubstitution || exit
[ -d build/fml8/log4jsubstitution ] || mkdir -p build/fml8/log4jsubstitution || exit
set -x
for f in fml7/log4jsubstitution/ForgeMod.java fml8/log4jsubstitution/ForgeMod.java mcmod.info; do
	rm -f "build/$f"
	sed -E "s \\\$\\{modid\\} `printf %s \"$1\" | sed -E 's/([]?*% .{}^\$[+-])/\\\\\\1/g'` g" "$f" > "build/$f"
done
fml7_class_path=/opt/minecraft/forge-1.7.10-10.13.2.1291-universal.jar
fml8_class_path=/opt/minecraft/forge-1.11.2-13.20.1.2386-universal.jar
cd build
pids=
for d in fml7 fml8; do {
	trap "echo '$d build failed' 1>&2" EXIT
	eval "class_path=\$${d}_class_path"
	i=0
	until ln -f mcmod.info $d/; do i=$((i+1)); [ $i -lt 8 ]; done
	[ $i -gt 0 ] && echo "mcmod.info linked successfully after retrying" 1>&2
	cd $d
	"$JDK_HOME/bin/javac" -source 1.6 -target 1.6 -classpath $class_path log4jsubstitution/ForgeMod.java
	rm -f bad-forge-mod-name.jar
	7za a -tzip bad-forge-mod-name.jar log4jsubstitution/ForgeMod.class mcmod.info
	trap - EXIT
} & pids="$! $pids"
done
wait $pids
