#!/bin/bash

#this script will backup all winlink messages
#to an external thumb drive. You can specify
#the exact path when starting the file or allow
#the script to look for an external drive automatically.
#To specify a path, add it when calling the script.
#example /home/pi/bin/mail-backup ~/Downloads
#28DEC2020 KM4ACK

#sleep for 30 seconds while pi boots
sleep 30

#set archive folder
#DO NOT USE SPACES. Use "-" or "_" to serperate words.
ARCH=old-email-backups

#set a few variables
CALL=$(grep MYCALLSIGN ~/patmenu2/config | sed 's/MYCALLSIGN=//')
BKUPTIME=$(date +%Y%m%d-%H%M)
DATE=$(date)

#check to see if user indicated path
#use external drive if not
if [ -z $1 ]; then
DIR=$(ls /media/pi)
	#verify we have a path or external drive to work with
	if [ -z $DIR ] && [ -z $1 ]; then
	echo "External drive not found and backup directory not specified." 
	echo "$DATE Winlink backup failed. Path not set and external drive not found" >> $HOME/Documents/mylog.txt
	exit 1
	fi
DIR=/media/pi/$DIR
else
DIR=$1
fi

#create archive dir
mkdir -p $DIR/$ARCH

#move old backups to archive dir
mv $DIR/email.bkup* $DIR/$ARCH/ >/dev/null 2>&1

#create backup dir
mkdir $DIR/email.bkup.$BKUPTIME

#copy file to backup dir
cp -r $HOME/.wl2k/mailbox/$CALL/* $DIR/email.bkup.$BKUPTIME

#verify success and write to log file
if [ $? = 0 ]; then
echo "$DATE Winlink messages back up success" >> $HOME/Documents/mylog.txt
else
echo "$DATE Winlink backup failed" >> $HOME/Documents/mylog.txt
fi

