#!/bin/bash

export BIN_PATH=$(dirname "$0")
export CX_BOTTLE=easyct64

WP_DIR=$("$BIN_PATH/wine" --wait-children --bottle $CX_BOTTLE winepath "C:\\")

# Migrate any old registry entries, if necessary
OLD_REG_FILE=$WP_DIR/.reg-migrated.txt

if [ ! -f "$OLD_REG_FILE" ]; then
	OLD_BOTTLE=$WP_DIR/../../easyct

	if [ -d "$OLD_BOTTLE" ]; then
		TMP_FILE=$TMPDIR/`uuidgen`.reg

		sed -n '/\[Software\\\\Thomas Mielke Softwareentwicklung\\\\EasyCash&Tax\\\\.*\] */,/^$/p' "$OLD_BOTTLE/user.reg" > "$TMP_FILE.tmp"

		if [ -s "$TMP_FILE.tmp" ]; then
			echo "Windows Registry Editor Version 5.00" > "$TMP_FILE"
			echo "" >> "$TMP_FILE"

			cat "$TMP_FILE.tmp" \
				| sed -e '/^#/d' -e 's/C:\\\\users\\\\crossover\\\\My Documents/C:\\\\users\\\\crossover\\\\Documents/i' \
				| sed -e '/^#/d' -e 's/C:\\\\Program Files\\\\EasyCash/C:\\\\Program Files \(x86\)\\\\EasyCash/i' \
				| perl -pe 's/\[Software\\\\Thomas Mielke Softwareentwicklung\\\\EasyCash&Tax\\\\([\w\ \.\-]+)(\\(\\)([\w\ \.\-]+))?\] (\d*)/[HKEY_CURRENT_USER\\Software\\Thomas Mielke Softwareentwicklung\\EasyCash&Tax\\\1\3\4]/' \
				>> "$TMP_FILE"

			"$BIN_PATH/wine" --bottle $CX_BOTTLE --wait-children regedit "$TMP_FILE"
			rm "$TMP_FILE"
		fi

		rm "$TMP_FILE.tmp"
	fi

	touch "$OLD_REG_FILE"
fi

# File to indicate whether first-run has completed
FIRST_RUN_FILE=$WP_DIR/.first-run-complete.txt

if [ ! -f "$FIRST_RUN_FILE" ]; then
	read -r -d '' applescriptCode <<'EOF'
		display alert "Bitte die mitzuinstallierenden Formulare auswählen" buttons {"Deutsche", "Österreichische"} default button "Deutsche"
		if button returned of result = "Deutsche" then
			return "de"
		else
			return "at"
		end if
EOF

	FORMULA_LANG=$(osascript -e "$applescriptCode")

	pushd "$WP_DIR/Program Files (x86)/EasyCash&Tax/"
	rsync -aL "../../formula/$FORMULA_LANG/"* .
	popd

	touch "$FIRST_RUN_FILE"
else
	pushd "$WP_DIR/Program Files (x86)/EasyCash&Tax/"

	FILES_FOUND=$(find . -maxdepth 1 -iname 'U1-at-*.ecf' | wc -l)

	if [ $FILES_FOUND -gt 0 ]; then
		FORMULA_LANG=at
	else
		FORMULA_LANG=de
	fi

	rsync -aL "../../formula/$FORMULA_LANG/"* .
	popd

fi

"$BIN_PATH/wine" --enable-alt-loader=macdrv --wait-children --bottle $CX_BOTTLE --workdir 'c:/Program Files (x86)/EasyCash&Tax' EasyCT.exe
