#!/bin/bash

ROOTDIR="$(pwd)"
# TuxGuitar Program Version
TGPV="1.6.0"
#TGPV="9999"
# Other TuxGuitar related variables
TGDIR="tuxguitar-${TGPV}"
BUILD_SCRIPT_DIR="build-scripts/tuxguitar-linux-swt-x86_64"

# TuxGuitar need its own swt version
SWTDIR="swt-4.13-gtk-linux-x86_64"
SWTURI="https://archive.eclipse.org/eclipse/downloads/drops4/R-4.13-201909161045/"
SWTZIP="swt-4.13-gtk-linux-x86_64.zip"
if [ ! -d .m2 ]; then
	# For portage to be happy and emerge to work, we need to use
	# a m2 directory inside $WORKDIR with the -s option of mvn.
	echo Create maven m2 directory...
	mkdir -p .m2
	echo Copy the installed marven settings.xml file...
	cp "$(equery f maven-bin|grep settings.xml)" .m2
	echo Patching that file with the custom m2 PATH...
	awk '/<localRepository>/ {line = $0; next}; /-->/ && line { print; print line; line="";next}; {print}' < .m2/settings.xml > .m2/settings.xml.new
	sed -e "s:/path/to/local/repo:$(pwd)/.m2:" < .m2/settings.xml.new > .m2/settings.xml
	rm .m2/settings.xml.new
fi

echo Downloading and extracting swt...
if [ ! -e "${SWTZIP}" ]; then
	wget "${SWTURI}${SWTZIP}"
else
	echo "${SWTZIP} exist, skipping download..."
fi

if [ ! -d "${SWTDIR}" ]; then
	mkdir "${SWTDIR}"
	cd "${SWTDIR}"
	unzip ../"${SWTZIP}"
	mvn -s /home/dom/softs/Gentoo/TuxGuitar/.m2/settings.xml -Dfile=swt.jar -DgroupId=org.eclipse.swt -DartifactId=org.eclipse.swt.gtk.linux.x86_64 -Dpackaging=jar -Dversion=4.13 install:install-file
	cd "${ROOTDIR}"
else
	echo swt directory exist, skipping...
fi

# download TuxGuitar
TGARCHIVE="${TGPV}.tar.gz"
echo "Downloading TuxGuitar ${TGPV}..."
if [ ! -e "${TGARCHIVE}" ]; then
	#git clone https://github.com/helge17/tuxguitar.git tuxguitar-9999
	wget https://github.com/helge17/tuxguitar/archive/refs/tags/"${TGARCHIVE}"
else
	echo "TuxGuitar ${TGARCHIVE} exist, skipping..."
fi

if [ ! -d "${TGDIR}" ]; then
	tar -xvzf ${TGARCHIVE}
else
	echo TuxGuitar directory exist, skipping...
fi

# download VST2 headers
echo "Downloading VST2 header files"
if [ ! -d VST2 ]; then
	mkdir VST2
	cd VST2
	for hfile in aeffect.h aeffectx.h vstfxstore.h; do
		wget https://raw.githubusercontent.com/R-Tur/VST_SDK_2.4/master/pluginterfaces/vst2.x/$hfile
	done
	cd "${ROOTDIR}"
else
	echo "VST2 directory exist, skipping download..."
fi

echo "InstaLLing VST header files..."
VSTDIR="${TGDIR}/build-scripts/native-modules/tuxguitar-synth-vst-linux-x86_64/include"
if [ ! -d "${VSTDIR}" ]; then
	mkdir "${VSTDIR}"
	cp VST2/* "${VSTDIR}"
else
	echo "VST TuxGuitar directory exist, skipping install..."
fi

# build TuxGuitar
cd "${TGDIR}/${BUILD_SCRIPT_DIR}"
echo Building TuxGuitar...
mvn -e clean verify -s /home/dom/softs/Gentoo/TuxGuitar/.m2/settings.xml -P native-modules

# Launch it!
cd target/tuxguitar-*
./tuxguitar.sh
cd "${ROOTDIR}"

# Make a m2 archive
echo "Making an archive of the marven dependencies..."
tar -cvjSf tuxguitar-"${TGPV}"_bdepends.tar.bz2 .m2 VST2
