#!/bin/bash

while true; do
    sudo -E /usr/local/bin/camera_server &> /data/.cs.log 
    exit_loop=$?
    echo "Camera Server exit status: $exit_loop"

    # The exit status of 115 ('s') means to shutdown.
    if [ "$exit_loop" = "115" ]; then
	sync; sync

	# Make sure we unmount the head's SSD.
	# It may not be mounted, but we need to make sure.
	sudo /usr/local/sbin/nvme-automount remove /dev/nvme0n1p1

	# Flush the block devices
	sudo /usr/bin/blockdev --flushbufs /dev/nvme0n1

	# Tell the FPGA to turn off the camera head.
	echo "w 0x1BC 0x3210ABCD" > /proc/fi_pci/regs
	sleep 1

	# Now shutdown.
	sudo shutdown -h now
    fi

    # An exit status of 82 ('R') measn to reboot
    if [ "$exit_loop" = "82" ]; then
	sync; sync

	# Request a reboot.
	sudo shutdown -r now
    fi

    # Is the camera server asking for a restart?
    # The exit status of 114 ('r') means to reboot. 
    if [ "$exit_loop" != "114" ]; then
	exit 0
    fi
done
