#!/bin/bash

echo "This is installation of package for platform $1"

# defaults
platform_bits=32 # platform bits can be 32 or 64 or arm
mode_silent=0
cam_currera_enabled=0
cam_usb30_enabled=0
pcie_enabled=0
h264_enabled=1
api_version=2
this_is_x32=0
this_is_x64=0
this_is_arm=0

function PrintUsage()
{
	echo "Usage: install_steps -x64|-x32|-arm [-silent] [-cam_currera] [-cam_usb30] [-pcie] [-nonet]"
}

# parsing arguments
parsed=0
for arg in $*
do
	if [ "$arg" == "-x64" ]
	then
		platform_bits=64
		this_is_x64=1
		parsed=1
	fi
	if [ "$arg" == "-x32" ]
	then
		platform_bits=32
		this_is_x32=1
		parsed=1
	fi
	if [ "$arg" == "-arm" ]
	then
		platform_bits=arm
		this_is_arm=1
		parsed=1
	fi
	if [ "$arg" == "-silent" ]
	then
		mode_silent=1
		parsed=1
	fi
	if [ "$arg" == "-nonet" ]
	then
		h264_enabled=0
		parsed=1
	fi
	if [ "$arg" == "-cam_currera" ]
	then
		cam_currera_enabled=1
		parsed=1
	fi
	if [ "$arg" == "-cam_usb30" ]
	then
		cam_usb30_enabled=1
		parsed=1
	fi
	if [ "$arg" == "-pcie" ]
	then
		pcie_enabled=1
		parsed=1
	fi
	if [ "$arg" == "-m3api" ]
	then
		api_version=0
		parsed=1
	fi
	if [ $parsed == 0 ]
	then
		echo "Invalid argument $arg"
		PrintUsage
		exit 1
	fi
done

if [ $parsed == 0 ]
then
	PrintUsage
	exit 1
fi

echo Checking if user is super user
if [ $EUID == 0 ]
then
    echo OK
else
    echo Please run: sudo ./install_steps
    exit 1
fi

function Check()
{
    if [ $? == 0 ]
    then
	echo OK
    else
	echo Error on previous command
	exit 1
    fi
}

optpath=/opt/XIMEA
mkdir -p $optpath/bin $optpath/lib $optpath/src $optpath/CamTool 2>/dev/null
cp version_LINUX_SP.txt $optpath

# -----------------------------------------------------------------------------

echo Installing and reloading udev rules
groupadd -fr plugdev
Check
cp libs/libusb/99-ximea.rules /etc/udev/rules.d/
Check
udevadm control --reload
Check

# -----------------------------------------------------------------------------

if [ $pcie_enabled == 1 ]
then
	echo Building and installing PCIe driver
	echo This requires compiler and kernel sources to be installed
	cp -R src/ximea_cam_pcie $optpath/src/
	pushd $optpath/src/ximea_cam_pcie
	make clean
	Check
	make
	Check
	make install
	Check
	depmod
	Check
	echo Reloading kernel module, will fail if it is in use
	rmmod ximea_cam_pcie 2>/dev/null
	modprobe --first-time ximea_cam_pcie
	Check
	popd
	echo Please note that after upgrading the kernel you need to rebuild PCIe kernel driver
	echo To do that either re-run this installation script after booting into new kernel
	echo or run the following commands from root account:
	echo "$ cd $optpath/src/ximea_cam_pcie"
	echo "$ make clean && make KERNEL=<new_kernel_version> && make KERNEL=<new_kernel_version> install"
	echo "$ modprobe ximea_cam_pcie"
	echo KERNEL= argument is needed when building for kernel version different from currently running
fi

# -----------------------------------------------------------------------------

if [ $cam_currera_enabled == 1 ]
then
	echo Loading currera kernel module
	mkdir $optpath/modules 2>/dev/null
	cp modules/currera_acq.ko $optpath/modules
	cp -R src/currera_acq_module $optpath/src/

	# add start script
	initscr=/etc/init.d/currera_init
	cp scripts/currera_init $initscr
	chmod a+x $initscr
	Check
	# set script as enabled
	echo Enabling driver start script
	update-rc.d currera_init defaults 2>/dev/null

	echo Starting Driver
	$initscr stop
	$initscr start

	echo Setting driver node
	chmod a+rw /dev/cura0
	Check
	echo Note - the module currera_acq.ko must be loaded before API library is used.
fi

# -----------------------------------------------------------------------------
# install our versions of libusb and libraw1394 to /lib so they always get priority

# -----------------------------------------------------------------------------

libusbversion=vanilla
KV=$(uname -r).
if [ "${KV:0:$(($(expr index $KV .)-1))}" -lt 3 ] || \
	[ "${KV:$(expr index $KV .):$(($(expr index ${KV:$(expr index $KV .)} .)-1))}" -lt 6 ]
then
	if [ $cam_usb30_enabled == 1 ]
	then
		if [ "${KV:0:$(($(expr index $KV .)-1))}" -lt 3 ] || \
			[ "${KV:$(expr index $KV .):$(($(expr index ${KV:$(expr index $KV .)} .)-1))}" -lt 4 ]
		then
			echo "-------------------------------------"
			echo "CAUTION!!!"
			echo "Your current Linux kernel version is too old for USB3 support!!!"
			echo "Minimum required version is 3.4."
			echo "If you proceed with installation, USB support will be broken system-wide until you upgrade the kernel!!!"
			echo "Advised way of enabling USB3 support is upgrading kernel to version at least as new as 3.6."
			echo "If you decide to do it in the future, rerun this installation script after rebooting into new kernel."
			echo "-------------------------------------"
			if [ $mode_silent == 0 ]
			then
				echo "Press Enter to continue or Ctrl-C to exit"
				read
			fi
		else
			echo "-------------------------------------"
			echo "WARNING!!!"
			echo "You have enabled experimental USB3 support! It may affect USB2 support too."
			echo "DO NOT downgrade the kernel to versions older than 3.4!!!"
			echo "Advised way of enabling USB3 support is upgrading kernel to version at least as new as 3.6."
			echo "If you decide to do it in the future, rerun this installation script after rebooting into new kernel."
			echo "-------------------------------------"
			sleep 5
		fi
		libusbversion=
	else
		echo "-------------------------------------"
		echo "USB3 support for kernels older than 3.6 is experimental and disabled by default."
		echo "You have to request it explicitly by running installation script with -cam_usb30 option."
		echo "Be aware that you will need kernel version not older than 3.4!"
		echo "Advised way of enabling USB3 support is upgrading kernel to version at least as new as 3.6."
		echo "-------------------------------------"
	fi
fi

echo Installing libusb
cp -d libs/libusb/"$libusbversion"X$platform_bits/lib* /lib/
Check

# remove now unneeded and causing troubles workaround
if grep -qs '^; workaround for kernels 3\.12 & 3\.13$' $optpath/config.ini
then
	sed -e '/^; workaround for kernels 3\.12 & 3\.13$/ d' -e '/^PPTB = 1008$/ d' -i $optpath/config.ini
fi

# -----------------------------------------------------------------------------

if [ "$this_is_arm" == "0" ]
then
echo Installing Firewire support - libraw1394
cp -d libs/libraw1394/X$platform_bits/lib*.so* /lib/
Check

echo Checking Firewire stack
modprobe configs &>/dev/null
juju=n
ieee=n
if [ -e /proc/config.gz ]
then
	juju=$(zgrep CONFIG_FIREWIRE= /proc/config.gz | cut -d= -f2)
	ieee=$(zgrep CONFIG_IEEE1394= /proc/config.gz | cut -d= -f2)
elif [ -e /lib/modules/$(uname -r)/build/.config ]
then
	juju=$(grep CONFIG_FIREWIRE= /lib/modules/$(uname -r)/build/.config | cut -d= -f2)
	ieee=$(grep CONFIG_IEEE1394= /lib/modules/$(uname -r)/build/.config | cut -d= -f2)
fi
if [ "$juju" != "y" ] && [ "$juju" != "m" ] || [ "$juju$ieee" == "my" ] || [ "$juju$ieee" == "mm" ]
then
	echo "-------------------------------------"
	echo Your current Linux configuration does not support XIMEA Firewire cameras
	echo For Firewire cameras support you need to enable config option CONFIG_FIREWIRE in kernel.
	echo Older kernels have another implementation of Firewire stack - CONFIG_IEEE1394, which is unsupported.
	echo Make sure that the right one is used. 
	echo
	echo More information about this can be found here:
	echo http://www.ximea.com/support/wiki/apis/Linux_Firewire_Support
	echo "-------------------------------------"
	if [ $mode_silent == 0 ]
	then
		echo Press Enter to continue
		read choice
	fi
fi
fi

echo
echo Installing API library

cp api/X$platform_bits/libm3api.so.0 /usr/lib/libm3api.so.0.0.0 && \
cp api/X$platform_bits/libm3api.so.2 /usr/lib/libm3api.so.2.0.0 && \
ln -snf libm3api.so.$api_version /usr/lib/libm3api.so
Check

cp -R include $optpath/ && \
cp -R examples $optpath/
Check

ln -snf ../../opt/XIMEA/include /usr/include/m3api
Check

echo
echo Rebuilding linker cache
echo /lib > /etc/ld.so.conf.d/000XIMEA.conf
echo /usr/lib >> /etc/ld.so.conf.d/000XIMEA.conf
ldconfig

echo Installing XIMEA-GenTL library
cp libs/gentl/X$platform_bits/libXIMEA_GenTL.cti.$api_version $optpath/lib/libXIMEA_GenTL.cti
Check

echo Installing xiSample
cp bin/xiSample.$platform_bits $optpath/bin/xiSample
Check

if [ "$this_is_arm" == "0" ]
then
if [ -e bin/vaViewer.$platform_bits ]
then
echo Installing vaViewer
cp bin/vaViewer.$platform_bits $optpath/bin/vaViewer
Check
fi

echo Installing streamViewer
cp bin/streamViewer.$platform_bits $optpath/bin/streamViewer
Check

if [ -d "$(eval echo ~$SUDO_USER/Desktop)" ]
then
echo Creating desktop link for streamViewer
newlauncher="$(eval echo ~$SUDO_USER/Desktop/streamViewer.desktop)"
echo "[Desktop Entry]" >$newlauncher
echo "Version=1.0" >>$newlauncher
echo "Type=Application" >>$newlauncher
echo "Terminal=false" >>$newlauncher
echo "Icon[en_US]=gnome-panel-launcher" >>$newlauncher
echo "Name=streamViewer" >>$newlauncher
echo "Exec=$optpath/bin/streamViewer" >>$newlauncher
chmod a+x $newlauncher
fi

if [ -e CamTool.$platform_bits ]
then
echo Installing CamTool
cp bin/xiCamTool $optpath/bin/
Check
cp -R CamTool.$platform_bits/* $optpath/CamTool
Check
if [ "$h264_enabled" == "1" -a ! -e $optpath/CamTool/libopenh264-1.4.0-linux$platform_bits.so ]
then
echo Downloading OpenH264 library
curl -fLo $optpath/CamTool/libopenh264-1.4.0-linux$platform_bits.so.bz2 http://ciscobinary.openh264.org/libopenh264-1.4.0-linux$platform_bits.so.bz2 && \
bunzip2 $optpath/CamTool/libopenh264-1.4.0-linux$platform_bits.so.bz2 || echo "Failed"
fi
if [ ! -e $optpath/CamTool/libopenh264-1.4.0-linux$platform_bits.so ]
then
echo "-------------------------------------"
echo "For instructions on how to enable H264 encoding support in xiCamTool, please see the following link:"
echo "http://www.ximea.com/support/wiki/allprod/XIMEA_CamTool_OpenH264_Library"
echo "-------------------------------------"
fi

if [ -d "$(eval echo ~$SUDO_USER/Desktop)" ]
then
echo Creating desktop link for xiCamTool
newlauncher="$(eval echo ~$SUDO_USER/Desktop/xiCamTool.desktop)"
echo "[Desktop Entry]" >$newlauncher
echo "Version=1.0" >>$newlauncher
echo "Type=Application" >>$newlauncher
echo "Terminal=false" >>$newlauncher
echo "Icon[en_US]=gnome-panel-launcher" >>$newlauncher
echo "Name=xiCamTool" >>$newlauncher
echo "Exec=$optpath/bin/xiCamTool" >>$newlauncher
chmod a+x $newlauncher
fi

fi

fi

echo "-------------------------------------"
echo Note:
echo You may need to reconnect your USB and/or Firewire cameras
echo Also check that you are in the \"plugdev\" group
echo
echo More info:
echo http://www.ximea.com/support/wiki/apis/Linux_USB20_Support
echo "-------------------------------------"
sleep 5

echo "-------------------------------------"
if [ "$this_is_arm" == "0" ]
then
echo "For GeniCam - please add \"export GENICAM_GENTL"$platform_bits"_PATH=$optpath/lib/\" to your ~/.bashrc to enable GenTL"
fi
echo "Now applications can be started. E.g. $optpath/bin/xiSample"
echo "-------------------------------------"

echo Done OK
