#!/bin/bash
set -e
set -x

# create a new ZFS filesystem for the target
# look for all the rnspashots and sort by date
# from oldest, rsync it into the ZFS and then snapshot it with a name that matches its old date and tag it matching old name

if [ -z "$1" ] 
then
 echo usage: $0 fqdn [zpool]
 exit 1
fi

which bc >/dev/null || ( echo "Could not find bc command"; exit 1 )

function ensurezpool() {
 if [ -n "$1" ]
 then
  echo $1
 else
  ( for z in $(zpool list -H -oname)
  do 
   zfs list -H -p -oavail,name $z
  done ) | sort -nr | head -1 | cut -f2
 fi
}

function ensurelv() {
 LV=$(lvs -o lv_path --noheadings -S "lv_name=$1" | head -1 |sed 's/  *//')
 if [ -z "$LV" ]
 then
  echo Cannot find LV for $SN
  exit 2
 fi
 echo $LV
}

function mount_lv() {
 mkdir -p /rsnapshots/$2
 mount $LV /rsnapshots/$2 2>/dev/null || echo already mounted
}

function umount_lv() {
 HN=$1
 make -f /usr/local/rsnapshots/Makefile ${HN}-umount || umount -l /rsnapshots/$HN
}

function ensure_zfs() {
 ZPOOL=$1
 HN=$2
 QUOTA=$3
 ZFS=$(zfs list -H -d1 -oname | grep $HN)
 if [ -n "$ZFS" ]
 then
  >&2 echo ZFS $ZFS already exists, using that 
 else
  ZFS=$ZPOOL/$HN
  zfs create $ZFS
  zfs create $ZFS/zfs-rsnap
 fi
 zfs set quota=$QUOTA $ZFS
 echo $ZFS
}

function get_quota() {
 SIZE=$(lvs --no-headings -osize --units=b $1 | sed 's/  *//' | sed 's/B$//')
 printf "%.0f\n" $(echo $SIZE*1.1 | bc)
}

function sync_backups() {
 HN=$1
 ZFS=$2
 TARGETDIR=$ZFS/zfs-rsnap
 SOURCEDIR=/rsnapshots/$HN
 for incremental in $(ls -tr $SOURCEDIR | grep -v 'lost+found')
 do
  TIME=$(stat -c "%Y" $SOURCEDIR/$incremental)
  if ! zfs list -t snapshot ${TARGETDIR}@${TIME} >/dev/null
  then
   rsync -aq --delete $SOURCEDIR/$incremental/ /$TARGETDIR
   TAG=$(echo $incremental | sed 's/\.[0-9]//')
   zfs snapshot ${TARGETDIR}@${TIME}
   zfs hold $TAG ${TARGETDIR}@${TIME}
 else
   echo Already synced ${TARGETDIR}@${TIME}
 fi 
 done
}

ZPOOL=$(ensurezpool $2) 
HN=$1
SN=$(echo $HN | sed 's/\..*$//')
LV=$(ensurelv $SN)
QUOTA=$(get_quota $LV)
mount_lv $LV $HN
ZFS=$(ensure_zfs $ZPOOL $HN $QUOTA)
sync_backups $HN $ZFS

echo $HN $SN $ZPOOL $LV $ZFS $QUOTA

umount_lv $HN
if [ -f /etc/rsnapshot.conf.d/$HN ]
then
  /usr/lib/chem-zfs-backup-server/new-backup-rsnapshot $HN
  mv /etc/rsnapshot.conf.d/$HN /etc/rsnapshot.conf.d/attic
fi
rmdir /rsnapshots/${HN}
