#!/bin/bash

# include configuration
. "$(dirname "$0")/config.sh"


# verify the operation parameter
op="$2"
if [ -z "$op" ]; then
    echo "Missing params. Instance and operation are required" >&2
    exit 1
fi
shift
shift

####### Operations
case "$op" in
    restart-rt)
        #Restart runtime
        echo "Restarting mervisrt"
        systemctl restart --no-block mervisrt
        exit 0
        ;;
    restart-request)
        # Temporary call of update until new RT will be available
          . "$lib/ctl-update.sh"
          sleep 1
        #Restart all services
        echo "Restarting mervisrt and mervisconfigtool"
        systemctl restart --no-block  mervisrt mervisconfigtool
        exit 0
        ;;
    reboot-request)
        #Restart machine
        echo "Rebooting the PLC"
        sync
        /sbin/reboot
        exit 0
        ;;
    sync)
        #called after changes in filesystem
        . "$lib/ctl-sync.sh"
        exit 0
        ;;
    start-services)
        #Start fcgi
        echo "Starting mervisfcgi"
        systemctl start mervisfcgi
        exit 0
        ;;
    stop-services)
        #Stop fcgi
        echo "Stoping mervisfcgi"
        systemctl stop mervisfcgi
        exit 0
        ;;
    update-system)
        . "$lib/ctl-update.sh"
        exit 0
        ;;
    service)
        #Configure services
        #continue later
        ;;
    *)
        echo "Unknown operation $op" >&2
        exit 1
        ;;
esac


############### Configure services
service="$1"
shift
if [ -z "$service" ]; then
    echo "Missing service parameter" >&2
    exit 1
fi

case "$service" in
    webserver)
        echo "Service: webserver"
        . "$lib/srv-webserver.sh"
        ;;

    netserver)
        # Do nothing. UNUSED
        echo "Service 'netserver'"
        . "$lib/srv-netserver.sh"
        ;;

    sshserver)
        echo "Service: ssh"
        . "$lib/srv-ssh.sh"
        ;;

    telnetserver)
        # do nothing. UNUSED
        echo "Ignoring service 'telnetserver'"
        ;;

    cloudaccess)
        echo "Service: cloudaccess"
        . "$lib/srv-cloudaccess.sh"
        ;;
    commit)
        echo "Service: commit"
        ;;
    *)
        echo "Unknown service $service" >&2
        exit 1
        ;;
esac

exit 0
