#!/usr/bin/env bash

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

if [[ $# -eq 2 && -e $1 && $2 =~ [0-9]+ ]]; then
  # ls -1 /tmp/manuskriptbackups/ | wc -l
  rollto=$(find /tmp/manuskriptbackups/ -name "*$1.*" -cmin +$2 | sort | tail -n1)
  if [[ -n $rollto ]]; then
    if [[ `pgrep -f "manuskript $1"` ]]; then
      echo $1 is still open in Manuskript
    else
      mv $BOOK_DIR/$1 $BOOK_DIR/$1.$(date +"%Y-%m-%d_%H:%M:%S")
      mv $rollto $BOOK_DIR/$1
      echo $1 rolled back to $rollto
    fi
  else
    echo There is no backup of $1 from more than $2 minutes ago.
  fi
else
  echo
  echo "USAGE : rollback FILE N"
  echo
  echo " FILE : .msk file"
  echo "    N : minutes to roll back"
  echo
fi
