#!/bin/bash

info() { printf "\n%s %s\n\n" "$( date )" "$*" >&2; }
trap 'echo $( date ) Backup interrupted >&2; exit 2' INT TERM

backup_name="{{ key }}"

{% if job.mountpoint is defined -%}
export MOUNTPOINT="{{ job.mountpoint|default('/mnt') }}"

if [[ $(mountpoint -q $MOUNTPOINT) -ne 0 ]]
then
  info "Mountpoint not exists, exiting backup"
  exit 2
fi

repo_path=${MOUNTPOINT}/borg
{% else %}
repo_path={{ job.sshrepo|default('localhost::tmp') }}
{%- endif %}

export BORG_REPO=$repo_path/${backup_name}
export BORG_PASSPHRASE='{{ job.password }}'

info "Starting backup"

info "Init repository backup"
borg init --encryption={{ job.encryption|default('repokey-blake2') }}

info "Starting before tasks"
{%- for task in job.before_tasks|default([]) %}
{{ task }}
{%- endfor %}

info "Creating new archive"
borg create         \
    --verbose       \
    --filter AME    \
    --list          \
    --stats         \
    --show-rc       \
    --compression {{ job.compression|default('lz4') }}  \
{%- if job.excluded_dirs is defined -%}
{%- for exclude in job.excluded_dirs %}
    --exclude '{{ exclude }}'           \
{%- endfor %}
{%- endif %}
    --exclude-caches                    \
    ::$backup_name'-{hostname}-{now}'   \
{%- for include in job.included_dirs %}
    {{ include }} \
{%- endfor %}
    2>> {{ log_dir }}/${backup_name}-$(date +%Y-%m-%d).log

backup_exit=$?

info "Pruning repository"
borg prune              \
    --list              \
    -a $backup_name'-'  \
    --show-rc           \
    --keep-daily        {{ job.keep_daily|default(7) }}    \
    --keep-weekly       {{ job.keep_weekly|default(4) }}   \
    --keep-monthly      {{ job.keep_monthly|default(6) }}  \

info "Cleaning up logs"
find {{ log_dir }}/${backup_name}-*.log -mtime +{{ job.keep_logs_days|default(7) }} -delete

info "Starting after tasks"
{%- for task in job.after_tasks|default([]) %}
{{ task }}
{%- endfor %}

prune_exit=$?

global_exit=$(( backup_exit > prune_exit ? backup_exit : prune_exit ))

if [ ${global_exit} -eq 0 ]; then
    info "Backup and Prune finished successfully"
elif [ ${global_exit} -eq 1 ]; then
    info "Backup and/or Prune finished with warnings"
else
    info "Backup and/or Prune finished with errors"
fi

exit ${global_exit}