#! /bin/sh -e

. /etc/init.d/functions.sh

start_module() {
	local sysdir=/sys/class/firmware/altera_fpga.0
	local sysdir2=/sys/devices/platform/altera_fpga.0/firmware/firmware-altera_fpg
	local sysdir3=/sys/devices/platform/altera_fpga.0/firmware/altera_fpga.0
	local fw_data=/lib/firmware/fpga_fw.rbf

	insmod altera_fpga_ps fpga_reset_pin=131102

	# wait maximum 5 seconds for directories to become available
	local max_nbr=250
	while [ ! -d $sysdir ] && [ ! -d $sysdir2 ] && [ ! -d $sysdir3 ] && [ $max_nbr -gt 0 ]; do
		usleep 200000
		max_nbr=$(($max_nbr - 1))
	done

	[ -d $sysdir ] || sysdir=$sysdir2
	[ -d $sysdir ] || sysdir=$sysdir3

	echo 1	    > $sysdir/loading
	cp $fw_data   $sysdir/data
	echo 0	    > $sysdir/loading
}

stop_module() {
	rmmod altera_fpga_ps
}

case "$1" in
	start)
		begin "Loading the Altera FPGA module"
		start_module
		end $?
		;;
	stop)
		begin "Removing the Altera FPGA module"
		stop_module
		end $?
		;;
	restart|force-reload)
		begin "Reloading the Altera FPGA module"
		stop_module && start_module
		end $?
		;;
	*)
		error "Usage: $0 start|stop|restart|force-reload"
		;;
esac

exit 0
