#!/bin/bash
# A script which runs, largely on the remote machine, to prepare for backup
# Jobs to do: 
# * Exclude files which are only found in packages
# * List all packages which are installed
# * (optionally) dump MySQL into a file
# * (optionally) dump PostgreSQL into a file
SERVER=$1
if [ -z $SERVER ] ; then
 echo $0 Server
 exit 1
fi
(
# Has the package status changed since last time we generated the list of files?
if ssh root@$SERVER [ /var/lib/dpkg/status -nt /var/adm/backup/package-files ] ; then
 # Need to rebuild package-files
 ssh root@$SERVER "
  umask 077
  FILELIST=\`tempfile\`
  CONFLIST=\`tempfile\`
  mkdir -p /var/adm/backup
  # Which packages are installed?
  dpkg --get-selections | awk ' { print \$1 ; } ' >/var/adm/backup/packages
  cat /var/lib/dpkg/info/*.list | while read F ; do [ -f \"\$F\" ] && echo \"\$F\" ; done | sort > \$FILELIST
  awk '/Description:/ { flag = 0 } ; flag == 1 { print \$1 ; }  ; /Conffiles:/ { flag = 1  } ; ' </var/lib/dpkg/status |  sort >\$CONFLIST
  diff -u \$FILELIST \$CONFLIST | grep ^-/ | sed s/^-// >/var/adm/backup/package-files
 "
 mkdir -p /etc/rsnapshot/$SERVER
 scp -q root@$SERVER:/var/adm/backup/package-files /etc/rsnapshot/$SERVER/exclude
fi

ssh root@$SERVER "
# Ensure that things are not readable where they ought not to be
umask 077

# Save the package configuration info
which debconf-get-selections >/dev/null 2>&1 || apt-get install debconf-utils
which rsync >/dev/null 2>&1 || apt-get install rsync
debconf-get-selections  >/var/adm/backup/debconf

# Dump MySQL, if the root user has access
if [ -f /etc/mysql/my.cnf ] ; then
 SOCKET=`awk ' BEGIN {FLAG=0} (\$0 ~ /^\[/) {FLAG=0} (\$0 ~ /^\[mysqld\]/) {FLAG=1} (\$1=="socket" && FLAG==1) { print \$3 ; } ' </etc/mysql/my.cnf`
 [ -S \$SOCKET ] && which mysqldump >/dev/null 2>&1 && mysqldump  --defaults-file=/etc/mysql/debian.cnf --all-databases >/var/adm/backup/mysql
fi

# Dump PostgresSQL, if the postgres user has access
id postgres >/dev/null 2>&1 && [ -d /var/run/postgresql/ ] && [ -x /usr/bin/pg_dumpall ] && ( su -c 'pg_dumpall --oids --clean' postgres >/var/adm/backup/postgres || echo Postgres failed on $SERVER )

# Dump LDAP, if we can
which slapcat >/dev/null 2>&1 && slapcat >/var/adm/backup/ldap

# Ignore exit status of this command
true
"
echo Prepared $SERVER `date`
) >/var/log/rsnapshots/$SERVER 2>&1
