#!/bin/bash
# Partimaged launcher 
# Gabriel Marques
# snortt@gmail.com
# Thu 24 Nov 2022 12:49:02 AM EST
# 

me=$(id -u)

if [ "$me" -ne "0" ]; then
    echo "I need to be root"
    exit 
fi

LOG="/var/log/partimage-server.log"

help() {
    echo "Usage: $(basename $0) start|stop|status"
}

case $1 in 
    "start")
        
        pid=$(pidof partimaged 2> /dev/null)
        if [ -n "$pid" ]; then
            echo "partimage is already running ($pid)"
            exit 
        fi

        # Target dir
        TARGET="/mnt/externo/OS_Images"

        # Port for remote clients
        PORT="4025"

        # Concurrent connections
        CLIENTS="3"

        SRV_OPTS="--daemon --dest ${TARGET} --port=${PORT} --number=${CLIENTS} --nossl --nologin --debug=3 "

        # ---------------------------------------------
        SERVER="$(which partimaged)"

        echo -e "Starting partimaged with options \n $SRV_OPTS" > $LOG
        date >> $LOG 

        ${SERVER} ${SRV_OPTS} >> ${LOG} 2>&1 
        ;;

    "stop")
        pid=$(pidof partimaged 2> /dev/null)
        if [ -z "$pid" ]; then
            echo "partimage is not running"
            exit 
        fi

        kill $(pidof partimaged) 2> /dev/null && echo "$SERVER stoped" >> $LOG 
        ;;

    "status")
        pid=$(pidof partimaged)

        if [ "$?" -eq "0" ]; then
            echo "partimaged is running ($pid)"
        else
            echo "partimaged is not running"
        fi
        ;;

    *)
        help
        exit
        ;;
esac

