#!/bin/bash
# ------------------------------------------------------------------
# AUTHOR: [LucidLink Support]
# NAME: lucid_systemd.sh
# VERSION: 1.0.2
# DESCRIPTION: systemd Lucid install and management script.
#
# THE SCRIPT IS PROVIDED “AS IS” AND “AS AVAILABLE” AND IS WITHOUT
# WARRANTY OF ANY KIND. PLEASE REVIEW ALL TERMS AND CONDITIONS.
# https://www.lucidlink.com/legal-documents
# ------------------------------------------------------------------

USAGE="
Usage: ./lucid_systemd.sh [options]
Request failed with: Bad Request

Lucid options:

     --instance <id>                 Daemon instance.
     --fs <filespace.domain>         Filespace and domain name (required).
     --user <fsusr>                  Filespace username.
     --password <fsusrpwd>           Filespace user password.
     --mount-point <mount>           Filespace mount-point.
     --all-snapshots                 Activate in snapshots mode.
     --snapshot <id>                 Activate the snapshot instead of the live Filespace.
     --root-path <rootpath>          Root-path (metadata / cache) location.
     --config-path <configpath>      Config-path {Lucid.log .json) location.
     --fuse-allow-other              Allow other users on this machine to access the filesystem.

systemd options:

     --sysd-user <sysdusr>           systemd unit user.
     --sysd-group <sysdgroup>        systemd unit group.
     --sysd-workdir <sysdwkdir>      systemd unit working directory.
     --sysd-file <unitfile>          systemd service file.

Advanced options:

     --list <unitfile>               List systemd service.
     --list-all                      List systemd services with description beginning 'LucidLink'.
     --start <unitfile>              systemctl start specified service.
     --status <unitfile>             systemctl status of specified service.
     --stop <unitfile>               systemctl stop specified service.
     --enable <unitfile>             systemctl enable specified service.
     --disable <unitfile>            systemctl disable specifed service.
     --daemon-reload                 systemctl daemon-reload.
     --remove <unitfile>             Remove disabled systemd service.
     --replace <unitfile>            Override existing systemd service.

Example: ./lucid_systemd.sh --fs filespace.domain --user root --password Abcd1234 --mount-point /media/lucid --sysd-user user --sysd-group group --sysd-workdir /home/user --sysd-file filespace-domain.service
"

if [ $# == 0 ] ; then
echo "$USAGE"
exit 1;
fi

HEADER_TOP="# ------------------------------------------------------------------
# AUTHOR: [LucidLink Support]"

HEADER_BOTTOM="# generated systemd unit file.
#
# THE SCRIPT IS PROVIDED “AS IS” AND “AS AVAILABLE” AND IS WITHOUT
# WARRANTY OF ANY KIND. PLEASE REVIEW ALL TERMS AND CONDITIONS.
# https://www.lucidlink.com/legal-documents
# ------------------------------------------------------------------"

INSTANCE=
FS=
USER=
PASSWORD=
ROOTPATH=
CONFIGPATH=

SHORT=n,a
LONG=instance:,fs:,user:,password:,mount-point:,all-snapshots,snapshot:,root-path:,config-path:,fuse-allow-other,sysd-user:,sysd-group:,sysd-workdir:,sysd-file:,list:,list-all,start:,status:,stop:,enable:,disable:,daemon-reload,remove:,replace:

OPTIONS=$(getopt --options $SHORT --long $LONG --name "$0" -- "$@")
if [ $? != 0 ] ; then echo "Failed to parse options...exiting." >&2 ; exit 1 ; fi
eval set -- "$OPTIONS"

while true ; do
  case "$1" in
    --instance )
      INSTANCE="$2"
      shift 2
      ;;
        --fs )
      FS="$2"
      shift 2
      ;;
    --user )
      USER="$2"
      shift 2
      ;;
    --password )
      PASSWORD="$2"
      shift 2
      ;;
    --mount-point )
      MOUNTPOINT="$2"
      shift 2
      ;;
    --all-snapshots )
      ALLSNAPSHOTS="--all-snapshots"
      shift
      ;;
    --snapshot )
      SNAPSHOT="$2"
      shift 2
      ;;
    --root-path )
      ROOTPATH="$2"
      shift 2
      ;;
    --config-path )
      CONFIGPATH="$2"
      shift 2
      ;;
    --fuse-allow-other )
      FUSEALLOWOTHER="--fuse-allow-other"
      shift
      ;;
    --sysd-user )
      SYSDUSER="$2"
      shift 2
      ;;
    --sysd-group )
      SYSDGROUP="$2"
      shift 2
      ;;
    --sysd-workdir )
      SYSDWORKDIR="$2"
      shift 2
      ;;
    --sysd-file )
      SYSDFILE="$2"
      shift 2
      ;;
    --list )
      LIST="$2"
      shift 2
      ;;
    --list-all )
      LISTALL="list-all"
      shift
      ;;
    --start )
      START="$2"
      shift 2
      ;;
    --status )
      STATUS="$2"
      shift 2
      ;;
    --stop )
      STOP="$2"
      shift 2
      ;;
    --enable )
      ENABLE="$2"
      shift 2
      ;;
    --disable )
      DISABLE="$2"
      shift 2
      ;;
    --daemon-reload )
      DAEMONRELOAD="daemon-reload"
      shift
      ;;
    --remove )
      REMOVE="$2"
      shift 2
      ;;
    --replace )
      REPLACE="$2"
      shift 2
      ;;
    -- )
      shift
      break
      ;;
    *)
      echo "Unknown option!"
      exit 1
      ;;
  esac
done

COMMAND="lucid2"

if [ -z "$SYSDFILE" ]
then
     FSSYSDFILE="${FS//./-}"
     SYSDFILE="$FSSYSDFILE.service"
else
if [[ "$SYSDFILE" == *.service ]]
then
     :
else
echo -e "\e[91mError: $SYSDFILE needs to end in .service\e[0m"
exit
fi
fi


if [ -z "$LIST" ]
then
     :
else
     systemctl list-unit-files "$LIST"
     exit
fi

if [ -z "$LISTALL" ]
then
     :
else
     LISTALL=$(find /etc/systemd/system/ -type f -iname "*.service" -execdir grep -l "Description=LucidLink" {} + | sed -r 's/^.{2}//' | tr '\n' ' ')
     if [ -z "$LISTALL" ]
     then
          LISTALL=none
     fi
     systemctl list-unit-files $LISTALL
     exit
fi

if [ -z "$START" ]
then
     :
else
     systemctl start "$START"
     exit
fi

if [ -z "$STATUS" ]
then
     :
else
     systemctl status "$STATUS" --no-pager
     exit
fi

if [ -z "$STOP" ]
then
     :
else
     systemctl stop "$STOP"
     exit
fi

if [ -z "$ENABLE" ]
then
     :
else
     systemctl enable "$ENABLE"
     exit
fi

if [ -z "$DISABLE" ]
then
     :
else
     systemctl disable "$DISABLE"
     exit
fi

if [ -z "$DAEMONRELOAD" ]
then
     :
else
     systemctl $DAEMONRELOAD
     exit
fi

if [ -z "$REMOVE" ]
then
     :
else
     systemctl stop $REMOVE
     systemctl disable $REMOVE
     rm /etc/systemd/system/$REMOVE
     systemctl daemon-reload
     exit
fi

if [ -z "$REPLACE" ]
then
     :
else
     systemctl stop $REPLACE
     systemctl disable $REPLACE
     rm /etc/systemd/system/$REPLACE
     systemctl daemon-reload
fi

if [ -n "$INSTANCE" ]
then
     COMMAND="$COMMAND --instance $INSTANCE daemon"
     INSTANCEID="--instance $INSTANCE"
     INSTANCEEXIT="--instance $INSTANCE"
else
     COMMAND="$COMMAND daemon"
fi

if [ -z "$FS" ]
then
     echo "Filespace '--fs filespace.domain' required!"
     exit
else
     COMMAND="$COMMAND --fs $FS"
fi

if [ -n "$USER" ]
then
     COMMAND="$COMMAND --user $USER"
fi

if [ -n "$PASSWORD" ]
then
     COMMAND="$COMMAND --password $PASSWORD"
fi

if [ -n "$MOUNTPOINT" ]
then
     COMMAND="$COMMAND --mount-point $MOUNTPOINT"
fi

if [ -n "$ALLSNAPSHOTS" ]
then
     COMMAND="$COMMAND $ALLSNAPSHOTS"
fi

if [ -n "$SNAPSHOT" ]
then
     COMMAND="$COMMAND --snapshot $SNAPSHOT"
fi

if [ -n "$ROOTPATH" ]
then
     COMMAND="$COMMAND --root-path $ROOTPATH"
fi

if [ -n "$CONFIGPATH" ]
then
     COMMAND="$COMMAND --config-path $CONFIGPATH"
fi

if [ -n "$FUSEALLOWOTHER" ]
then
     COMMAND="$COMMAND $FUSEALLOWOTHER"
     sed -i 's/#user_allow_other/user_allow_other/g' /etc/fuse.conf
     if grep -Pq '^(user_allow_other!?)' "/etc/fuse.conf"; then
       :
     else
       echo "user_allow_other" >>  /etc/fuse.conf
     fi

fi

if [ -n "$SYSDUSER" ]
then
     SYSDUSR="User=$SYSDUSER"
else
     SYSDUSR="#User=<user>"
fi

if [ -n "$SYSDGROUP" ]
then
     SYSDGRP="Group=$SYSDGROUP"
else
     SYSDGRP="#Group=<group>"
fi

if [ -n "$SYSDWORKDIR" ]
then
     SYSDWD="WorkingDirectory=$SYSDWORKDIR"
else
     SYSDWD="#WorkingDirectory=/home/<user>"
fi

CHECK_SYSDFILE=$(systemctl list-unit-files --type service | grep -wo $SYSDFILE)
if [ -f "/etc/systemd/system/$CHECK_SYSDFILE" ]; then
     echo -e "\e[91mError: $CHECK_SYSDFILE systemd unit file exists. use --replace option.\e[0m"
     exit
fi

if [ -e $SYSDFILE ] ; then
     :
else
     touch $SYSDFILE
fi

if [ -w $SYSDFILE ] ; then
     :
else
     echo -e "\e[91mError: write $SYSDFILE permission denied.\e[0m"
     exit
fi

echo
echo "systemd unit file '$SYSDFILE'"
echo
echo "$HEADER_TOP" | tee $SYSDFILE
echo "# NAME: $SYSDFILE" | tee -a $SYSDFILE
echo "# DESCRIPTION: luicd_systemd.sh $FS daemon" | tee -a $SYSDFILE
echo "$HEADER_BOTTOM" | tee -a $SYSDFILE
echo "[Unit]" | tee -a $SYSDFILE
echo "Description=LucidLink $FS Daemon" | tee -a $SYSDFILE
echo "After=network-online.target" | tee -a $SYSDFILE
echo "[Service]" | tee -a $SYSDFILE
echo "$SYSDUSR" | tee -a $SYSDFILE
echo "$SYSDGRP" | tee -a $SYSDFILE
echo "$SYSDWD" | tee -a $SYSDFILE
echo "ExecStart=/usr/bin/$COMMAND" | tee -a $SYSDFILE
echo "ExecStop=/usr/bin/lucid2 $INSTANCEEXIT exit" | tee -a $SYSDFILE
echo "Restart=on-abort" | tee -a $SYSDFILE
echo "[Install]" | tee -a $SYSDFILE
echo "WantedBy=multi-user.target" | tee -a $SYSDFILE
echo

echo "Moving 'mv $SYSDFILE /etc/systemd/system'"
mv $SYSDFILE /etc/systemd/system
wait
echo "Enabling 'systemctl enable $SYSDFILE'"
systemctl enable $SYSDFILE
wait
echo "Starting 'systemctl start $SYSDFILE'"
systemctl start $SYSDFILE
wait
echo

until lucid2 $INSTANCEID status | grep -qo "Linked"
do
lucid2 $INSTANCEID status
sleep 1
lucidrunning=$(lucid2 $INSTANCEID status 2> /dev/null) ; lucidnotrunning=$?
if [[ $lucidnotrunning -eq 75 ]]; then
break
fi
done

lucid2 $INSTANCEID status

sleep 1

echo
echo "Status 'systemctl status $SYSDFILE'"
systemctl status $SYSDFILE -n0 --no-pager
echo