#!/bin/bash

usage()
{
  echo "Usage: $0 [-p Backup_Path]"
  exit 2
}

borg_run() {
  echo "$PROGNAME: Starting backup ..."
  /usr/bin/flock /tmp/borg.lock /usr/bin/borg create $BORG_REPO::$ARCHIVE_NAME $ARCHIVE_SOURCE $BORG_CMD
  exit 0
}

set_variable()
{
  local varname=$1
  shift
  if [ -z "${!varname}" ]; then
    eval "$varname=\"$@\""
  else
    echo "Error: $varname already set"
    usage
  fi
}

####################################################################
# Main script starts here



while getopts 'p:?h' c
do
  case $c in
    p) set_variable ARCHIVE_SOURCE "$OPTARG" ;;
    h|?) usage ;; 
  esac
done

set_variable BORG_STATUS_STATUS ""
set_variable PROGNAME "$(basename "$0")"

export BORG_PASSPHRASE="eagle_squeezing_pretender_penny_residency_shifting_scoop_uninvited_bacon_tried"
set_variable BORG_REPO "/mnt/user/Cloud/bdrive/backup/ket/repo"
set_variable BORG_CONFIG_DIR "/mnt/user/appdata/borg/config"
set_variable BORG_CACHE_DIR "/mnt/disks/nvme/cache/borgmatic"
#set_variable ARCHIVE_SOURCE "/mnt/user/Homes/Denis/"
set_variable ARCHIVE_NAME $(date +"%Y%m%H%M%s")
BORG_CMD=" --compression none \
--list \
--info \
--progress \
--stats \
--exclude-if-present .nobackup \
--one-file-system \
--files-cache mtime,size " #--dry-run "
#echo "/usr/bin/borg create "$BORG_REPO::$ARCHIVE_NAME $ARCHIVE_SOURCE" "$BORG_CMD""

echo $ARCHIVE_SOURCE

borg_run



case "$BORG_STATUS" in
    0)
    # "INFO - No error occured."
    echo "$PROGNAME: Borg backup successfully executed"
    exit 0
    ;;
    1)
    # "WARNING - $CONTAINER state is restarting."
    echo "$PROGNAME: Error: Borg backup raised an error"
    exit 1
    ;;
esac