#!/bin/bash

#Author: Thaddeus M. Diede
#
# Bash Script: awsback-nscus-twicemonthly
#
# Created 2016-11-02
# Updated 2017-01-18 - Added condition for day of month, and fixed variables.
#
# This script is for creating and uploading a tar.gz archive of the
# /usr/ns/cus directory files to the TriLynx Client Amazon Web Services (AWS)
# S3 cloud storage

# Backups of this type are set to occur on the 1st and 15th of each month.

# Links are followed and a directory listing is stored in the archive
# to assist in rebuilding a corrupted /usr/ns/cus/ directory.

# The AWS command Line Interface tool is used to transfer the archive.

# aws-cli communicates on TCP Port 443 (the same as https/ssl).
# Make sure this port is open on the NovaStar system.

#------------------------------------------------------------------------------

# Configuration
PGNAME="awsbackup-nscus-twicemonthly"
PGDESC="Backup archive of /usr/ns/cus to AWS-S3 twice a month"
LOGFILE="/usr/ns/log/${PGNAME}.log"
NSCUSDIR="/usr/ns/cus"
BAKDIR="/usr/ns/bak"
# Used to tag backups so that AWS deletes old backups or moves them.
# There is not a twice monthly tag, so just use monthly.  Monthly backups are tranferred to Glacier after 180 days (about 6 months).
BACKUP_TYPE_TAG='monthly'

# Functions

cleanup() {
  SIGNAL=$?
  # Clean up temp files
  # Show exit code
  echo "Exit code: ${1:-$SIGNAL}"
}


# Main Program

# Trap signals
trap cleanup HUP INT QUIT ABRT TERM

# Send all output to log and screen
exec &> >(tee -a "$LOGFILE")

echo 
echo "***********************************************************"
echo "$(nstime) Starting $PGNAME..."

# Add path to aws-cli for cron to find it.
export PATH=$PATH:/usr/local/bin

echo "Loading Configuration file..."
# Load custom client config file settings
if [ ! -f /usr/ns/cus/awsbackup.config  ]; then
  echo "ERROR: Configuration not found!"
  exit 1
fi

source /usr/ns/cus/awsbackup.config

# Assign date variables and build the date code
DAYOFWEEK="$(date '+%u')"
DAYOFMONTH="$(date '+%d')"
DATECODE="$(date +%Y%m%d)"

echo "Day of month: $DAYOFMONTH"

if [ "$1" == '-f' ]; then
  echo "Force option detected, forcing backup.."
  DAYOFMONTH='01'
fi

# --------------------------------------------------------------
# Run twice a month on the 1st and the 15th
# --------------------------------------------------------------
if [ "$DAYOFMONTH" = 01 ] || [ "$DAYOFMONTH" = 15 ]; then
  # Set the S3 destination directory & nscus archive filename
  S3DIR="$CUSTCODE/NovaStar/nscusBackups"
  NSCUSFILE="$DATECODE-$CUSTCODE-$HOSTNAME-$NODECODE-nscusDir.tar.gz"
  # Store directory listing as an included README in the archive
  ls -la "$NSCUSDIR" > "$NSCUSDIR/DIRECTORY-LISTING-awsbackup-nscus.txt"
  # cd to backup directory and create archive.
  cd "$BAKDIR"
  tar -cvzhf "$NSCUSFILE" "$NSCUSDIR"
   
  # Upload the file to FTP Server, using datecode for remote filename.
  if [ "${FTP_SERVER:=none}" == "none" ] ; then
    echo "Skipping FTP upload per configuration."
  else
    echo "Uploading file $NSCUSFILE to $FTP_SERVER via FTP..."
    ftp -ni $FTP_SERVER << __EOF__
user $FTP_USERNAME $FTP_PASSWORD
cd $FTP_DIR
put $NSCUSFILE
quit
__EOF__

  fi

  echo "Uploading file $NSCUSFILE to S3..." 
  aws s3 cp "$NSCUSFILE" "s3://$S3BUCKET/$S3DIR/$NSCUSFILE" --profile "$AWSCLIPROFILE"
  echo "Tagging backup as $BACKUP_TYPE_TAG"
  aws s3api put-object-tagging --bucket $S3BUCKET --tagging "TagSet=[{Key=backup_type,Value=$BACKUP_TYPE_TAG}]" --key $S3DIR/$NSCUSFILE

else
  echo "$PGNAME not run today; Only performed on the 1st and 15th each month."
fi
echo "$(nstime) $PGDESC finished"
cleanup 0
