#!/bin/bash
clear

ROOT_UID=0
E_NOTROOT=67

if [ "$UID" -ne "$ROOT_UID" ]; then
    echo "To run the script require root privileges."
    exit $E_NOTROOT
fi

processor=$(uname -m)
param=$processor
if [ "$processor" == "x86_64" ]; then
    param="x86_64";
elif [[ $processor == *"86"* ]]; then
    param="x86";
else
    param="arm";
fi

dir1=$0 
basedir=$(dirname "$0")
cd "$basedir"

# echo stop service grdcontrold
if pgrep -x "grdcontrold" > /dev/null ; then
    sh /etc/init.d/grdcontrol stop
else
    rm -rf /var/run/grdcontrold.pid
fi

mkdir -p "/opt/guardant/grdcontrol/"

install -m 755 -g root -o root ./$param/grdcontrold /opt/guardant/grdcontrol

# copy license_wizard
install -m 755 -g root -o root ./$param/license_wizard /opt/guardant/grdcontrol
ln -sf /opt/guardant/grdcontrol/license_wizard       /usr/bin/license_wizard

# copy script
install -m 755 -g root -o root ./grdcontrol /etc/init.d

#copy properties file
install -m 644 -g root -o root ./grdcontrold.properties /opt/guardant/grdcontrol

#copy systemd configuration file
install -m 644 -g root -o root ./grdcontrol.service /opt/guardant/grdcontrol

#copy rules
install -m 644 -g root -o root ./95-grdnt.rules /etc/udev/rules.d

#copy www folder
cp -r  ./www /opt/guardant/grdcontrol/

if ps -C systemd | grep -q '^ *1 ' ;then

# reload udev
udevadm control --reload-rules
udevadm trigger --subsystem-match=usb --action=add

# make systemd config symbolic link
ln -sf /opt/guardant/grdcontrol/grdcontrol.service /etc/systemd/system/grdcontrol.service
# start service
systemctl -q start grdcontrol.service
# enable on boot
systemctl -q enable grdcontrol.service

else

# check OS type
if [ -e /etc/rc.d/init.d/functions ]; then
    INSTALL_OS="RedHat"
elif [ -e /etc/rc.status ]; then
    INSTALL_OS="SUSE"
elif [ -e /etc/debian_version ]; then
    INSTALL_OS="Debian"
else
    echo "Unsupported Linux distribution."
    exit 7
fi

# add control script to autorun
case $INSTALL_OS in 
SUSE)
    insserv grdcontrol
    ;;
Debian)
    update-rc.d grdcontrol defaults
    ;;
RedHat)
    /sbin/chkconfig --add grdcontrol
    ;;
esac

#start service grdcontrol
sh /etc/init.d/grdcontrol start

fi
