#!/bin/bash

function sleepExit() {
  if [ $ALERT_AT_END = "yes" ]
  then
    if [ $1 -eq 0 ]
    then
      ${ZENITY} --info --text "Backup successfully done!"
    else
      ${ZENITY} --error --text "Backup reported errors! Please check the terminal."
    fi
  fi
  exit $1
}

#
# commands
BTRFS=/sbin/btrfs
MKDIR=mkdir
RSYNC=rsync
CUT=cut
GREP=grep
HEAD=head
CHOWN=chown
ZENITY=zenity

#
# COLORS
RED="\033[31m"
GREEN="\033[32m"
NORMAL="\033[0m"

#
# check vars directory
dirName=$(dirname ${0})
CONFIG_FILE=${dirName}/.backup-config
if [ ! -r ${CONFIG_FILE} ]
then
  echo -e "${RED}Config file \"${CONFIG_FILE}\" does not exist. Cannot make the backup.${NORMAL}"
  sleepExit 1
fi
#
# load the config
. ${CONFIG_FILE}
#
# get the directory for the backup
hostDirName="${dirName}/${HOST_DIR}"
${MKDIR} -p ${hostDirName}
if [ $? -ne 0 ]
then
  echo -e "${RED}Directory \"${hostDirName}\" is not a directory. Cannot make the backup.${NORMAL}"
  sleepExit 1
fi
#
# create the hostname directory if it does not exist
hostName=$(hostname)
hostDirName="${hostDirName}/${hostName}"
if [ ! -e ${hostDirName} ]
then
  echo -e "${GREEN}Creating the subvolume \"${hostDirName}\".${NORMAL}"
  ${BTRFS} subvolume create ${hostDirName}
  if [ -n $SUDO_USER ]
  then
    ${CHOWN} ${SUDO_USER}: ${hostDirName}
  fi
fi
#
# check the hostname directory is a btrfs subvolume
${BTRFS} subvolume list ${hostDirName} >/dev/null 2>&1
if [ $? -ne 0 ]
then
  echo -e "${RED}Directory \"${hostDirName}\" is not a btrfs subvolume. Cannot make the backup.${NORMAL}"
  sleepExit 1
fi
#
# Perform the rsync over the subvolume
echo -e "${GREEN}Performing RSYNC from \"${SOURCE_BACKUP_DIR}\" to \"${hostDirName}\".${NORMAL}"
${RSYNC} -a --delete -v --stats --progress --exclude-from="${dirName}/${EXCLUDED_DIRS_FILE}" "${SOURCE_BACKUP_DIR}" "${hostDirName}"
if [ $? -ne 0 ]
then
  echo -e "${RED}Error executing the backup. Check previous errors.${NORMAL}"
  sleepExit 1
fi
#
# create a new snapshot
timestamp=$(date +%Y%m%d%H%M%S)
snapshotDirName=${hostDirName}-${timestamp}
echo -e "${GREEN}Creating snapshot from \"${hostDirName}\" into \"${snapshotDirName}\".${NORMAL}"
${BTRFS} subvolume snapshot "${hostDirName}" "${snapshotDirName}"
if [ $? -ne 0 ]
then
  echo -e "${RED}Error executing the snapshot of the backup.${NORMAL}"
  sleepExit 1
fi
if [ -n $SUDO_USER ]
then
  ${CHOWN} ${SUDO_USER}: ${snapshotDirName}
fi
#
# delete previous snapshots
num=$(${BTRFS} subvolume list ${dirName} | ${CUT} -d " " -f 7- | ${GREP} -c "${hostName}-")
num=$((${num} - ${MAX_SNAPSHOTS}))
if [ ${num} -gt 0 ]
then
  snapshots=$(${BTRFS} subvolume list ${dirName} | ${CUT} -d " " -f 7- | ${GREP} "${hostName}-" | ${HEAD} -n ${num})
  echo "${snapshots}" | while read snapshot
  do
    echo -e "${GREEN}Deleting previous snapshot \"${snapshot}\".${NORMAL}"
    ${BTRFS} subvolume delete ${snapshot}
  done
fi

echo -e "${GREEN}Backup successfully done!${NORMAL}"
sleepExit 0

