#!/usr/bin/bash


###
#
# Options Section
#
###

set -e
set -o pipefail


###
#
# Variable Section
#
###

export BORG_CACHE_DIR='/var/cache/borgbackup'
export BORG_CONFIG_EXCLUDE='/etc/borgbackup/exclude'
export BORG_CONFIG_FILE='/etc/borgbackup/config'
export BORG_KEYS_DIR='/etc/borgbackup/keys'
export BORG_LOG_DIR='/var/log/borgbackup'
export BORG_POSTEXEC_DIR='/etc/borgbackup/postexec'
export BORG_PREEXEC_DIR='/etc/borgbackup/preexec'
export BORG_SECURITY_DIR='/var/lib/borgbackup'
source '/etc/borgbackup/config'


###
#
# Function Section
#
###

function environment () {
  local INPUT
  local TYPE
  INPUT="${1}"
  /usr/bin/test -f "${INPUT}" && \
    TYPE='file'
  /usr/bin/test -d "${INPUT}" && \
    TYPE='directory'
  case "${TYPE}" in
    file)
      if [[ ! -f "${INPUT}" ]]; then
        INPUT=$(/usr/bin/basename "${INPUT}")
        /usr/bin/echo "ERROR: The required file '${INPUT}' could not be found."
        exit 1
      fi
    ;;
    directory)
      if [[ ! -d "${INPUT}" ]]; then
        INPUT=$(/usr/bin/realpath "${INPUT}")
        /usr/bin/echo "ERROR: The required directory '${INPUT}' could not be found."
        exit 1
      fi
    ;;
  esac
}

function configuration () {
  local INPUT
  INPUT="${1}"
  if [[ -z "${!INPUT}" ]]; then
    /usr/bin/echo "ERROR: The option '${INPUT}' is not set in configuration file."
    exit 1
  fi
}


###
#
# Runtime Environment
#
###

if [[ "${TIMER}" != 'true' ]]; then
  exit 1
fi
environment "${BORG_CACHE_DIR}"
environment "${BORG_CONFIG_EXCLUDE}"
environment "${BORG_CONFIG_FILE}"
environment "${BORG_KEYS_DIR}"
environment "${BORG_LOG_DIR=}"
environment "${BORG_POSTEXEC_DIR}"
environment "${BORG_PREEXEC_DIR}"
environment "${BORG_SECURITY_DIR}"
configuration 'BORG_REPO'
configuration 'BORG_COMPRESSION'
configuration 'BORG_PRUNE_WITHIN'
configuration 'BORG_PRUNE_DAILY'
configuration 'BORG_PRUNE_WEEKLY'
configuration 'BORG_PRUNE_MONTHLY'
configuration 'BORG_FILES_CACHE_TTL'
configuration 'BORG_SHOW_SYSINFO'
