#!/bin/sh

hulu="/opt/bin/huludesktop.bin"
config_file=$(echo ~/.huludesktop)

is_64bit()
{
	case $(file -L "$1") in
		*32-bit*) ;; # fall through
		*64-bit*) echo 64; return 0 ;;
		*) echo "unable to detect bitsize of $1" 1>&2 ;;
	esac
	echo 32
	return 1
}

find_flash()
{
	for d in \
		/usr/lib32/nsbrowser/plugins \
		/usr/lib/nsbrowser/plugins \
		/usr/lib64/nsbrowser/plugins \
	; do
		f="${d}/libflashplayer.so"
		if [ -e "${f}" ] && [ ${bit_hulu} = $(is_64bit "${f}") ] ; then
			echo ${f}
			return 0
		fi
	done
	echo ${f}
}

bit_hulu=$(is_64bit ${hulu})

if [ ! -e ${config_file} ] ; then
	# Create a stub file for people
	cat <<-EOF > ${config_file}
	[flash]
	flash_location = $(find_flash)
	EOF
else
	# Update the config file on the fly
	curr_flash=$(awk '$1 == "flash_location" { print $NF }' ${config_file})
	if [ ! -e "${curr_flash}" ] || [ ${bit_hulu} != $(is_64bit "${curr_flash}") ] ; then
		new_flash=$(find_flash)
		echo "Updating flash path:"
		echo "  old: ${curr_flash}"
		echo "  new: ${new_flash}"
		sed -i "/^flash_location/s:=.*:= ${new_flash}:" ${config_file}
	fi
fi

exec /opt/bin/huludesktop.bin "$@"
