#!/bin/bash

backup_dirs=(
  'share	/datas/			mouse.dmz.abrecht.li:/datas/'
  'git		/var/cache/git/		mouse.dmz.abrecht.li:/var/cache/git/'
  'mail		/vm/pelican/home/	pelican.dmz.abrecht.li:/home/'
)

backup_amounts=(
  'daily	%Y-%m-%d	 7'
  'weekly	%Y-%V		10'
  'monthly	%Y-%m		12'
  'yearly	%Y		 5'
)

eval "first=(${backup_amounts[0]})"

date="$(date +%Y-%m-%d)"
base="/backup"
newest="$(ls -1td "$base/${first[0]}"/*-*-*/ | head -n 1)"
today="$base/${first[0]}/$date"

if [ -d "$today" ]; then
  echo "Backup already exists"
  exit 1
fi

set -x
mkdir -p "$today"
set +x

for backup in "${backup_dirs[@]}"; do {
  eval "info=($backup)"
  archiv="${info[0]}"
  dst="${info[1]}"
  src="${info[2]}"
  set -x
  mkdir -p "$today/$archiv/$dst"
  rsync -az --delete --link-dest="$newest/$archiv/$dst" "$src" "$today/$archiv/$dst"
  set +x
} done

for i in $(seq 0 $(expr ${#backup_amounts[@]} - 2)); do {
  eval "src=(${backup_amounts[$i]})"
  eval "dst=(${backup_amounts[$(expr $i + 1)]})"
  source="$base/${src[0]}"
  dstname="${dst[0]}"
  destination="$base/$dstname"
  datepart="${dst[1]}"
  newestSource="$(basename "$(ls -1td "$source"/*-*-*/ 2>/dev/null | head -n 1)")"
  newestDestination="$(basename "$(ls -1td "$destination"/*-*-*/ 2>/dev/null | head -n 1)")"
  if [ -z "$newestSource" ]
    then continue
  fi
  if [ ! -z "$newestDestination" ]; then {
    datePartSource="$(date -d "$newestSource" "+$datepart")"
    datePartDestination="$(date -d "$newestDestination" "+$datepart")"
    if [ "$datePartSource" == "$datePartDestination" ]
      then continue
    fi
  } fi
  if [ ! -d "$destination" ]
    then mkdir -p "$destination"
  fi
  set -x
  mv "$source/$newestSource" "$destination/"
  ln -s "../$dstname/$newestSource" "$source/"
  set +x
} done

for backup in "${backup_amounts[@]}"; do {
  eval "info=($backup)"
  path="$base/${info[0]}"
  amount="${info[2]}"
  ls -1trd "$path"/*-*-*/ 2>/dev/null \
   | head -n "-$amount" \
   | while IFS='' read target
  do {
    set -x
    rm -r "${target%/}"
    set +x
  } done
} done

df -h /backup/
