#!/bin/bash
# Do all the backups (including HN), send to FTP but keep local copy, deal with purge, and nice output for mail
# Note: it uses uses non-standard file /backup.exclude in all VEs so VE users can
# write in it vzdump "--exclude-path" regexps in order not to backup useless
# things (typically /tmp and their storage directories)

# OpenVZ Directories
PRIVATE="/var/lib/vz/private"
DUMP="/var/lib/vz/dump"
# Also backup Hardware Node if on LVM - leave empty to disable
VG="vg5"
LV="rootfs"
# Local backups (keep a copy)
BACKUPS="/var/lib/vz/backups"
# GPG key
KEY="backups@stalkr.net"

# --- script
LOG="$DUMP/backup.log"

# Purge old backups, do it before to leave more backups most of the time
{ backup-purge; echo; } >$LOG

# Local copy
rm -rf $BACKUPS; mkdir $BACKUPS

echo "Starting backups on $(date)"
S=$(date '+%s')
E=0
R=0

# Backup Hardware Node & Containers
for I in 0 $(vzids -a); do
  echo -n " * $I ($(vzgetname $I))... "
  if [ $I -eq 0 ]; then
    # no backup if empty
    { [ -z "$VG" ] || [ -z "$LV" ]; } && continue
    # Hardware Node backup
    F=$DUMP/vzdump-openvz-0-$(date '+%Y_%m_%d-%H_%M_%S')
    { echo "Backup Hardware Node started"
      lvcreate -s -L 10G -n $LV-snap $VG/$LV && \
      mkdir -p /mnt/$LV-snap && mount /dev/$VG/$LV-snap /mnt/$LV-snap && \
      (cd /mnt/$LV-snap && tar czfp $F.tgz --sparse --numeric-owner --ignore-failed-read --one-file-system .)
      R=$?
      umount /mnt/$LV-snap
      lvremove -f $VG/$LV-snap
      echo "Backup Hardware Node ended"
    } 2>&1 |tee $F.log >>$LOG
  else
    # Containers backup using vzdump - configured in /etc/vzdump.conf
    B="$PRIVATE/$I/backup.exclude"
    if [ ! -f "$B" ]; then
      E=$[$E+1]
      echo "failed! No backup.exclude, aborted"
      continue
    fi
    vzdump --compress $(grep -v '^#' "$B" 2>/dev/null| awk '{print " --exclude-path "$0}') $I >>$LOG
    R=$?
  fi
  if [ $R -eq 0 ]; then
    gpg -e -r "$KEY" $DUMP/vzdump-openvz-$I-*.tgz
    if [ $? -eq 0 ] && [ -f $DUMP/vzdump-openvz-$I-*.tgz.gpg ]; then
      rm -f $DUMP/vzdump-openvz-$I-*.tgz
      echo -n "$(ls -lh $DUMP/vzdump-openvz-$I-*.tgz.gpg |awk '{print $5}')B... "
      ls -l $DUMP/vzdump-openvz-$I-* >>$LOG
      ftpbackup-send $DUMP/vzdump-openvz-$I-* >>$LOG
      if [ $? -eq 0 ]; then
        echo "OK"
      else
        E=$[$E+1]
        echo "failed"
      fi
    else
      E=$[$E+1]
      echo "failed! Error while encrypting"
      rm -f $DUMP/vzdump-openvz-$I-*.tgz
    fi
  else
    E=$[$E+1]
    echo "failed! Error while backup, see log for more info"
  fi
  # Local copy
  mv $DUMP/vzdump-openvz-$I-* $BACKUPS
done

D=$(duration $[$(date '+%s')-$S])
echo "Done backups, $E errors - Total time: $D"
echo "FTP space used: $(ftpbackup-du)"
echo

echo "--- Full log ---"
cat   $LOG
rm -f $LOG
