#!/bin/bash

export PATH=/usr:/sbin:/usr/bin:/usr/sbin:/usr/local/sbin
# ----------------------------------------------------------------------------
# FUNCTIONS
# ----------------------------------------------------------------------------

cleanup() {
if [ "y" == "$MYSQL" ]; then
  /bin/umount -f /var/lib/mysql-snapshot || true
  /sbin/lvremove -f /dev/vg0/mysql-snapshot || true
fi
}

mount_snapshot() {
  echo "mounting /var/lib/mysql-snapshot..."
  /bin/mkdir -p /var/lib/mysql-snapshot
  /bin/mount /dev/vg0/mysql-snapshot /var/lib/mysql-snapshot
  echo "mounted /var/lib/mysql-snapshot."
}

create_snapshot() {
  echo "locking database..."
  /usr/bin/mysql  --defaults-extra-file=/root/.my.cnf << EOF
FLUSH TABLES;
FLUSH TABLES WITH READ LOCK;
system /sbin/lvcreate --snapshot -n mysql-snapshot -L16G /dev/vg0/mysql
UNLOCK TABLES;
EOF
  echo "database locked"
}


# ----------------------------------------------------------------------------
# CONFIG
# ----------------------------------------------------------------------------

if [ ! -f /etc/systembackup.conf ]; then
  echo "systembackup not configured (/etc/systembackup.conf)"
  exit 1
fi

source /etc/systembackup.conf

if [ -z "$REPOSITORY" ]; then
  echo "REPOSITORY not set"
  exit 1
fi

if [ -z "$PASSPHRASE" ]; then
  echo "PASSPHRASE not set"
  exit 1
fi


# ----------------------------------------------------------------------------
# SETUP
# ----------------------------------------------------------------------------

set -e
trap cleanup SIGHUP SIGINT SIGTERM EXIT

if [ "y" == "$MYSQL" ]; then
  create_snapshot
  mount_snapshot
fi


# ----------------------------------------------------------------------------
# BACKUP
# ----------------------------------------------------------------------------

BORG_PASSPHRASE=$PASSPHRASE /usr/bin/nice -n 19 /usr/bin/ionice -c2 -n7 /usr/bin/borg create --stats -v \
    $REPOSITORY::'{hostname}-{now:%Y-%m-%d-%H}'    \
    / \
    --compression lzma \
    --exclude '/dev' \
    --exclude '/proc' \
    --exclude '/sys' \
    --exclude '/tmp' \
    --exclude '/run' \
    --exclude '/var/run' \
    --exclude '/mnt' \
    --exclude '/media' \
    --exclude 'lost+found' \
    --exclude '/var/cache/apt/archives/' \
    --exclude '/var/lib/lxcfs' \
    --exclude '/var/lib/mysql'


# ----------------------------------------------------------------------------
# PRUNE
# ----------------------------------------------------------------------------

BORG_PASSPHRASE=$PASSPHRASE /usr/bin/nice -n 19 /usr/bin/ionice -c2 -n7 /usr/bin/borg prune -v --list $REPOSITORY --prefix '{hostname}-' \
    --keep-hourly=6 --keep-daily=7 --keep-weekly=4 --keep-monthly=6