#!/bin/bash
# Script used to install the service for DV-Runtime
# Version 1.0
# Date 28.02.2020

arg=$1

systemd_dir="/etc/systemd/system"
unit_file_name="dv-runtime.service"
config_file="/etc/dv-runtime.xml"
log_file="/var/log/dv-runtime.log"
home_directory="/var/lib/dv-runtime"

user="dv-runtime"
group="dv-runtime"
mode="0644"
hmode="0755"

#--------------------------------------------------
if [[ -e ${systemd_dir}/${unit_file_name} ]] ; then
    sudo systemctl stop ${unit_file_name}
fi
#--------------------------------------------------
if [[ $arg == "-v" ]] ; then
    echo "Installing the service"
fi
sudo cp ${unit_file_name} ${systemd_dir}/
#--------------------------------------------------
if [[ $arg == "-v" ]] ; then
    echo "Change permission to service"
fi
sudo chmod ${mode} ${systemd_dir}/${unit_file_name}
#--------------------------------------------------
if [[ $arg == "-v" ]] ; then
    echo "Creating empty configuration files if not exists"
fi
if [[ ! -e ${config_file} ]] ; then
    sudo touch ${config_file}
fi
if [[ ! -e ${log_file} ]] ; then
    sudo touch ${log_file}
fi
#--------------------------------------------------
getent group ${group} > /dev/null
if [[ $? -ne 0 ]] ; then
    if [[ $arg == "-v" ]] ; then
        echo "Adding new group '${group}' for service"
    fi
    sudo groupadd ${group}
fi
getent passwd ${user} > /dev/null
if [[ $? -ne 0 ]] ; then
    if [[ $arg == "-v" ]] ; then
        echo "Adding new user '${user}' for service"
    fi
    sudo useradd -r -g ${group} -m -d ${home_directory} ${user}
fi
#--------------------------------------------------
if [[ $arg == "-v" ]] ; then
    echo "Change permission to configuration files"
fi
sudo chmod ${mode} ${config_file}
sudo chown ${user}:${group} ${config_file}
sudo chmod ${mode} ${log_file}
sudo chown ${user}:${group} ${log_file}
sudo chmod ${hmode} ${home_directory}
sudo chown ${user}:${group} ${home_directory}
#--------------------------------------------------
# Reload systemd manager configuration
sudo systemctl daemon-reload
#--------------------------------------------------

#sudo systemctl start ${unit_file_name}

echo "Now you can start the service with \"sudo systemctl start ${unit_file_name}\""
echo "If you want the service to start on boot, do \"sudo systemctl enable ${unit_file_name}\""
