#!/bin/sh

# This is a backup script that takes snapshots of your device
# In a Time Machine like fashion. You can add this to root's
# crontab for regular backups

# Config
readonly SSH_HOST=192.168.1.8
readonly SSH_USER=yigit
readonly SSH_KEY="/home/yigit/.ssh/id_skeleton"
readonly RSYNC_PROFILE="$SSH_USER@$SSH_HOST:~/snapshots"

alias ssh_cmd="ssh -i \"$SSH_KEY\" $SSH_USER@$SSH_HOST"

DEVICE=tatooine
OPT="-aPh"
SNAP="$RSYNC_PROFILE/$DEVICE/"
date=$(date "+%I:%M-%d.%m.%Y")
# You should enter absolute paths
DIRS="/home/yigit
/etc
/var/lib
/var/spool
/usr/src/linux"

# Check whether backup server is available on network
timeout 3 ssh -i "$SSH_KEY" $SSH_USER@$SSH_HOST id < /dev/null > /dev/null 2> /dev/null || echo "SSH Failed." || exit

# Run rsync to create snapshot
while IFS= read -r DIR
do
  LINK="--link-dest=/home/$SSH_USER/snapshots/tatooine/last$DIR/"
  ssh -i "$SSH_KEY" $SSH_USER@$SSH_HOST mkdir -p "~/snapshots/$DEVICE/$date$DIR" < /dev/null
  rsync --exclude '.cache' "$@" -e "ssh -i $SSH_KEY" $OPT "$LINK" "$DIR/" "${SNAP}$date$DIR/"
done << EOF
$DIRS
EOF

# Remove symlink to previous snapshot
ssh_cmd rm -f "~/snapshots/$DEVICE/last" < /dev/null

# Create new symlink to latest snapshot for the next backup to hardlink
ssh -i "$SSH_KEY" $SSH_USER@$SSH_HOST ln -s "~/snapshots/$DEVICE/$date" "~/snapshots/$DEVICE/last" < /dev/null
