#!/bin/bash
# backup-all.sh - Fetches backup from remote servers as specified in $backup_data

# Archives go here
mirror_dir="/edoceo/mirror/"

# Easy to put in file
backup_data=`/bin/grep -v '^#' ./backup-all.cfg`

for data in ${backup_data}; do
  host=`/bin/echo $data | /bin/cut -d'|' -f1`
  opts=`/bin/echo $data | /bin/cut -d'|' -f2`
  dirs=`/bin/echo $data | /bin/cut -d'|' -f3`

  # echo -e "Host: $host\n  Options: $opts\n  Dirs: $dirs\n"

  # If run on the first backup the host directory to tgz
  D=`/bin/date +%d`
  if [ "$D" = "01" ]; then
    X=`/bin/date +%Y-%m-%B`
    /bin/tar -cz -f ${mirror_dir}${host}-$X.tgz ${mirror_dir}${host}/* >/dev/null
  fi
  
  # If Database Selected
  /bin/echo "${opts}" | /bin/grep 'db' >/dev/null
  if [ "$?" = "0" ]; then
    # Backup the PostgreSQL databases
    DB_LIST=`ssh -2C ${host} "/usr/bin/psql -l -t -U postgres |/bin/cut -d'|' -f1 |/bin/sed -e 's/ //g'"`
    for DB in $DB_LIST
    do
      if [ "$DB" != "template0" ] && [ "$DB" != "template1" ]; then
        /usr/bin/ssh -2C ${host} "/usr/bin/pg_dump -b -f /home/edoceo/bak/$DB.pgd -Fc -U postgres $DB 2>/dev/null"
      fi
    done
  fi
  
  # Backup File Systems
  /bin/echo "${opts}" | /bin/grep 'fs' >/dev/null
  if [ "$?" = "0" ]; then
    # Sync the File Systems
    dirs=`echo $dirs | sed 's/:/\n/g'`
    for dir in ${dirs} ; do
      dst="${mirror_dir}${host}"
      if [ ! -d $dst ]; then
        /bin/mkdir -p $dst
      fi
      # Can say --bwlimit=56 or 128 to throttle
      /usr/bin/rsync -az -e ssh ${host}:$dir $dst
    done
  fi
done
