#!/bin/sh

basedir=$(dirname "$0")

##############################
### Darwin specific script ###
##############################

if [ "$(sw_vers -productVersion 2>/dev/null | cut -d. -f2)" -lt 9 ]; then
	echo "macOS version isn't supported $(sw_vers -productVersion 2>/dev/null | cut -d. -f1,2)"
	exit 1
fi

# 1. Decompress IBus files

tar xf "${basedir}/macOS-x11-CJK.tar.bz2" -C /opt/caldera/
chown -R caldera:wheel /opt/caldera/macOS_IBus_X11

# 2. Patch start script

for file in /opt/caldera/lib/DESKTOP/Actions/*
do
	if [ -x "$file" ]; then
		if ! grep -q "XMODIFIERS" "$file"; then
			cp "$file" "${file}.orig"
			awk '2; /#!\/bin\/sh/{print "\nif [ \"$(uname -s)\" = Darwin ]; then\n\texport XMODIFIERS=@im=ibus\nfi"}' "${file}.orig" > "${file}"
			rm "${file}.orig"
		fi
	fi
done

# 3. Make necessary link f r the current user

if [ -d "$HOME" ]; then
	if [ ! -d  "$HOME/.xinitrc.d" ]; then
		mkdir "$HOME/.xinitrc.d"
	fi
	if [ ! -e "$HOME/.xinitrc.d/ibus.sh" ]; then
		ln -s /opt/caldera/macOS_IBus_X11/share/caldera/ibus.sh "$HOME/.xinitrc.d/"
	fi
fi

# 4. Add shortcut for IBus Setup to the Desktop

if [ ! -e "$HOME/Desktop/IBus Setup.app" ]; then
	ln -s "/opt/caldera/macOS_IBus_X11/share/caldera/IBus Setup.app" "$HOME/Desktop"
fi

