#!/usr/bin/env bash

SCRIPT_DIR=$(dirname $(realpath $0))
BOOK_DIR=${SCRIPT_DIR/\/.Books/}

# PERIOD=10

mds() {
  md5sum "$1" | awk '{print $1}'
}

savey() {
  newhash=$(mds "$1")
  if [[ ! $newhash == $hash ]]; then
    cp "$1" "/tmp/manuskriptbackups/$1.$(date +"%Y-%m-%d_%H:%M:%S")"
    hash=$newhash
  fi
}


while [[ ! `pgrep -f "manuskript $1"` ]]; do
  sleep 0.5
done
notify-send "Making backups of $1 every $PERIOD seconds."
tick=1
hash=$(mds "$1")
while [[ `pgrep -f "manuskript $1"` ]]; do
  sleep 1
  if [[ $tick -ge $PERIOD ]]; then
    savey "$1"
    tick=0
  fi
  tick=$(( $tick + 1 ))
done
notify-send "No longer making backups of $1."
rm -f $BOOK_DIR/nohup.out
