#!/bin/bash
# paul@vandervlis.nl
# pull backup

# start
echo -e "\n`date +%T` Start backup"

# Remote IP:
RIP="10.0.1.3"
# Local DIR voor backup
LDIR="/backup/naam"
# Romote DIR voor backup
RDIR="/backup/localhost"
# Wat niet gebackupped hoeft te worden
EXCLUDE="\
--exclude=/mnt/** \
--exclude=/backup/** \
--exclude=/proc/** \
--exclude=/media/** \
--exclude=/tmp/** \
--exclude=/lost+found \
--exclude=/sys/** \
--exclude=/run/** \
--exclude=$RDIR \
--exclude=/var/cache/apt/archives/** \
--exclude=/home/*/.cache/** \
"

# mysqldump
echo -e "\n`date +%T` MySQL dump maken"
ssh $RIP "/usr/local/sbin/mysqlbackup"

# remote dagen opschuiven voor lokale backup daar
echo -e "\n`date +%T` Dagen opschuiven op te backuppen server"
ssh $RIP "\
if ! test -e $RDIR; then mkdir -p $RDIR; chmod 700 $RDIR; fi; \
cd $RDIR; \
if test -e backup-06; then rm -r backup-06; fi; \
if test -e backup-05; then mv backup-05 backup-06; fi; \
if test -e backup-04; then mv backup-04 backup-05; fi; \
if test -e backup-03; then mv backup-03 backup-04; fi; \
if test -e backup-02; then mv backup-02 backup-03; fi; \
if test -e backup-01; then mv backup-01 backup-02; fi; \
if test -e backup-00; then cp -al backup-00 backup-01; fi \
"

# lokaal synchroniseren
echo -e "\n`date +%T` Lokaal synchroniseren"
ssh $RIP "\
if ! test -e $RDIR; then mkdir -p $RDIR; chmod 700 $RDIR; fi; \
cd $RDIR; \
if test ! -e backup-00; then mkdir backup-00; fi; \
nice /usr/bin/rsync -a --del --delete-excluded $EXCLUDE / backup-00/; \
touch backup-00; \
"

# Hier dagen opschuiven
echo -e "\n`date +%T` Dagen opschuiven"
if ! test -e $LDIR; then mkdir -p $LDIR; chmod 700 $LDIR; fi;
cd $LDIR;
if test -e backup-06; then rm -r backup-06; fi;
if test -e backup-05; then mv backup-05 backup-06; fi;
if test -e backup-04; then mv backup-04 backup-05; fi;
if test -e backup-03; then mv backup-03 backup-04; fi;
if test -e backup-02; then mv backup-02 backup-03; fi;
if test -e backup-01; then mv backup-01 backup-02; fi;
if test -e backup-00; then cp -al backup-00 backup-01; fi;

#syncen naar remote
echo -e "\n`date +%T` Syncen naar backup-server:"
if ! test -e $LDIR; then mkdir -p $LDIR; chmod 700 $LDIR; fi
cd $LDIR
nice /usr/bin/rsync -azve /usr/bin/ssh --numeric-ids --del \
   $RIP:$RDIR/backup-00 ./

# klaar
echo -e "\n`date +%T` Backup klaar."

