paulbsd-salt/states/borg/templates/borg_job.sh.j2
2023-12-04 22:34:29 +01:00

94 lines
2.4 KiB
Django/Jinja

#!/bin/bash
info() { printf "\n%s %s\n\n" "$( date )" "$*" >&2; }
trap 'echo $( date ) Backup interrupted >&2; exit 2' INT TERM
backup_name="{{ name }}"
{% if params.mountpoint is defined -%}
export MOUNTPOINT="{{ params.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={{ params.sshrepo|default('localhost::tmp') }}
{%- endif %}
export BORG_REPO=$repo_path/${backup_name}
export BORG_PASSPHRASE='{{ params.password }}'
if [[ $1 == "list" ]]
then
borg list
exit
fi
info "Starting backup"
info "Init repository backup"
borg init --encryption={{ params.encryption|default('repokey-blake2') }}
info "Starting before tasks"
{%- for task in params.before_tasks|default([]) %}
{{ task }}
if [ $? -ne 0 ]; then echo error; fi
{%- endfor %}
info "Creating new archive"
borg create \
--verbose \
--filter AME \
--list \
--stats \
--show-rc \
--compression {{ params.compression|default('lz4') }} \
--exclude-if-present '.nobackup' \
{%- if params.excluded_dirs is defined -%}
{%- for exclude in params.excluded_dirs %}
--exclude '{{ exclude }}' \
{%- endfor %}
{%- endif %}
--exclude-caches \
::$backup_name'-{hostname}-{now}' \
{%- for include in params.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 {{ params.keep_daily|default(7) }} \
--keep-weekly {{ params.keep_weekly|default(4) }} \
--keep-monthly {{ params.keep_monthly|default(6) }} \
info "Cleaning up logs"
find {{ log_dir }}/${backup_name}-*.log -mtime +{{ params.keep_logs_days|default(7) }} -delete
info "Starting after tasks"
{%- for task in params.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}