#!/bin/bash
# This file is a simple script that start / stop / restart 
# services which is used from launchers
# It use menuexecg to start / stop / restart services and 
# show a notification to user
# The idea is we get rid of terminal with no useful usage
# author: Nong Hoang Tu <dmknght@parrotsec.org>

# Excepted usage: servicexc <name> <start / stop / restart>

source "$(dirname "$0")/error_exit"
export PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin:$PATH

[[ $# -ne 2 ]] && error_exit "Usage: servicexc <name> <start|stop|restart>" $E_INVALID_ARGS

service_name="$1"
service_action="$2"

# Validate if service exist
systemctl list-units --type=service --all | grep -q "$service_name" || \
    error_exit "Service '$service_name' not found" $E_COMMAND_NOT_FOUND

service_status="$(systemctl is-active $1)"
service_title="$service_name $service_action"
# Check status of current service
# If it is started, do not start it again
# if it is not started, do not stop or restart

if [ "$service_action" = "start" ] && [ "$service_status" = "active" ] ; then
  /usr/bin/notify-send "$service_title error" "$service_name is already activated!"
  exit
fi

if ([ "$service_action" = "stop" ] || [ "$service_action" == "restart" ]) && [ "$service_status" = "inactive" ] ; then
  /usr/bin/notify-send "$service_title error" "$service_name is not started!"
  exit
fi

if ! "/usr/sbin/service" "$service_name" "$service_action"; then
    error_exit "Failed to $service_action service $service_name" $E_SERVICE_ERROR
fi

service_status="$(systemctl is-active $1)"
# This is the command to show notification without icon
notify "$service_name $service_status" "Command \"$service_name $service_action\" executed"
