#!/bin/bash
### BEGIN INIT INFO
# Provides:          Load Moitessier HAT driver
# Required-Start:    $all
# Required-Stop:     $all
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Loads the Moitessier HAT driver during booting.
# Description:       
### END INIT INFO

# You need to copy load_driver_moitessier.sh to /etc/init.d before adding the service
# Add service: sudo update-rc.d -f load_driver_moitessier defaults
# Remove service: sudo update-rc.d -f load_driver_moitessier remove
#
# Error and info messages will be written to the kernel ring buffer.
# sys> dmesg

# get kernel release
kernelRelease=$(uname -r)
# get machine
machine=$(uname -m)

# You might need to change the path to the driver
driverPath=/home/pi/moitessier/modules/moitessier_${kernelRelease}.ko

# Shutdown script
#shutdownScript=/home/pi/moitessier/scripts/system_shutdown
#pidShutdownScript=0
#shutdownService=/etc/systemd/system/moitessier.shutdown.service
shutdownService=moitessier.shutdown.service     # do not use full path, see https://stackoverflow.com/questions/47856974/systemd-service-start-fails-no-service-mount-unit

# The device file used for the TTY interface
ttyDev=/dev/moitessier.tty

# Path to device tree related information
hatName=$(tr -d '\0' </proc/device-tree/soc/spi@7e204000/moitessier@0/name)

# Path to script killing any running process accessing the moitessier driver
killScript=/home/pi/moitessier/scripts/kill

# Path to the boot configuration
bootConfig=/boot/config.txt

# boot configuration strings to check
bootConfigSpiOn='spi=on';
bootConfigSpiOff='spi=off';
bootConfigI2COn='i2c_arm=on'
bootConfigI2COff='i2c_arm=off'
bootConfigOk=0

start() {
    if [ $? -ne 0 ]
    then
        echo "moitessier: HAT not available" > /dev/kmsg
        exit 1
    fi
    
    if [[ $hatName != *"moitessier"* ]]; then
        echo "moitessier: HAT not available" > /dev/kmsg
        exit 1
    fi
    
    bootConfig=$(cat ${bootConfig})
    if [ $? -ne 0 ]
    then
        echo "moitessier: configuration not available" > /dev/kmsg
        exit 1
    fi
    if [[ "$bootConfig" == *"$bootConfigSpiOn"* && "$bootConfig" != *"$bootConfigSpiOff"* ]];then
        if [[ "$bootConfig" == *"$bootConfigI2COn"* && "$bootConfig" != *"$bootConfigI2COff"* ]];then
            bootConfigOk=1
        fi
    fi
    
    if [ $bootConfigOk -ne 1 ]
    then
        echo "moitessier: Driver not loaded. You need to ensure that SPI and I2C are enabled." > /dev/kmsg
        exit 1
    fi
    
    echo "Loading $driverPath" > /dev/kmsg
    insmod $driverPath
    if [ $? -ne 0 ]
    then
        echo "moitessier: Could not load $driverPath." > /dev/kmsg
        exit 1
    fi
    # we need to sleep a while otherwise changing owner and access mode fails.
    sleep 3
    chown pi:pi $ttyDev
    if [ $? -ne 0 ]
    then
        echo "moitessier: Could not set owner for $ttyDev. You might need super user rights to access the device." > /dev/kmsg
        exit 1
    else
        echo "moitessier: Setting owner for $ttyDev." > /dev/kmsg
    fi
    chmod 666 $ttyDev
    if [ $? -ne 0 ]
    then
        echo "moitessier: Could not set access mode for $ttyDev. You might need super user rights to access the device." > /dev/kmsg
        exit 1
    else
        echo "moitessier: Setting access mode for $ttyDev." > /dev/kmsg
    fi
    
    #${shutdownScript} &
    #pidShutdownScript=$!
    running=$(systemctl list-units --type=service | grep moitessier.shutdown.service)
    if [ $? -ne 0 ]
    then
        echo "moitessier: moitessier.shutdown.service not running. Starting service now." > /dev/kmsg
        sudo systemctl start ${shutdownService}    
    else
        echo "moitessier: moitessier.shutdown.service already running." > /dev/kmsg
    fi
    pidShutdownScript=$(pgrep system_shutdown)
    echo "moitessier: PID shutdown=${pidShutdownScript}" > /dev/kmsg   
}
stop() {
    echo "Unloading $driverPath" > /dev/kmsg
    #if [ $pidShutdownScript -ne 0 ]
    #then
    #    kill $pidShutdownScript
    #    pidShutdownScript=0
    #fi
    sudo systemctl stop ${shutdownService}
    
    sudo ${killScript}
    
    sudo rmmod moitessier
    if [ $? -ne 0 ]
    then
        echo "moitessier: Unloading kernel module failed." > /dev/kmsg
        exit 1
    fi   
}

case "$1" in
    start)
        start;;
    stop)
        stop;;
    restart)
        stop
        start;;
    *)
        echo "Usage: $0 {start|stop|restart}"
        exit 1;;
esac
exit $?

