#!/bin/bash


#This script written by Shane Daley M0VUB. The script gracefully shutsdown services while services are cleaned and logs are truncated.
#We can also add items in this script for future use like updates or further log trims.
#Add to the cron tab for auto execution

#   Copyright (C) 2020 Shane P, Daley  M0VUB <support@gb7nr.co.uk>
#
#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation; either version 3 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.

#This script is for FreeDMR Server only which has been installed from docker_install.sh. It is NOT to be used for DOCKER-COMPOSE.
#NOT TO BE USED FOR DOCKER-COMPOSE INSTALL! PLEASE USE ALTERNATIVE FLUSH SCRIPT FOR FREEDMR THAT HAS BEEN INSTALLED WITH DOCKER-COMPOSE.

#Start service clean/truncate/ and restart of services.

echo Stopping services.....
sleep 2

echo Stopping FreeDMR Server....
docker container stop freedmr &&
echo Done.
sleep 1

echo Stopping HBMonitor
systemctl stop hbmon &&
echo Done.
sleep 1

echo FreeDMR Flush and maintenance cycle starting.....
sleep 1

echo Starting truncate main log folder /var/log.....
truncate -s 0 /var/log/*log &&

echo Starting truncate freedmr entire log /var/log/freedmr.....
truncate -s 0 /var/log/freedmr/*log &&

echo Starting truncate Lastheard.....
truncate -s 0 /opt/HBMonv2/log/*log &&

#Restart all services gracefully
echo Restart all services.....
sleep 2

echo Restarting docker app.....
systemctl restart docker &&
echo Done.
sleep 3

echo Restarting FreeDMR container.....
docker container start freedmr &&
echo Done.
sleep 2

#This basically ensures that docker has been updated to ensure that it reboots when dies.
echo FreeDMR container Set to restart on boot...
docker update --restart unless-stopped freedmr &&
echo Done.
sleep 1

#Lets flush the network address table so it picks up the connections quicker.
echo Flushing NAT.....
conntrack -F
echo Done.
sleep 1

echo Restart apache2.....
systemctl restart apache2 &&
echo Done.
sleep 1

echo Restart HBMonitor
systemctl restart hbmon &&
echo Done.
sleep 2

echo Finished.
sleep 1
echo All systems have been flushed/cleaned and ready to go. Aka Dr. Node. ShaYmez, DV-Scotland
