#!/usr/bin/env bash

BOOK_DIR="$(cat $HOME/.Books/bookdir)"

lb=$(echo -e '\033[38;5;94m')
db=$(echo -e '\033[38;5;95m')
blank=$(echo -e '\033[0m')
bold=$(echo -e '\033[1m')


#check if any instances of write.sh FORKED or manuskript are running first
if (ps -ef | grep -v grep | grep manuskript &>/dev/null); then
  echo "You need to exit Manuskript before you roll back."
  exit 1
fi
pkill -f "write.sh FORKED"

cd $BOOK_DIR

if ! (git log --oneline | grep -n autosave | grep -v HEAD &>/dev/null); then
  echo "Nothing to roll back to."
  exit
fi

echo "==============================================="

now=$(date +%s)

git log --oneline | grep -n autosave | grep -v HEAD | head -n 10 | while read line; do
  ln=${line%%:*}
  savetime=$(date -d "$(echo $line | awk '{print $2 " " $3}')" +%s)
  ago=$(( (now - savetime) / 60 ))
  echo "${bold}${lb}${ln}${blank}@${db}$(date -d @$savetime +'%a %d %b %H:%M:%S')${blank}@${lb}${ago} minutes ago"
done | column -s@ -t --table-columns Save,Time, --table-right Save

echo $db
read -ep " Choose a save to roll back to: $lb" saveno
echo
ddate=$(git log --oneline | grep -n --color=always autosave | grep --color=always -v HEAD | head -n $saveno | tail -n1 | awk '{print $2 " " $3}' | xargs -I@ date -d '@')
read -sn1 -p "$db Restore save from${lb} ${ddate}${db}? [y|N]" yn
if [ ${yn,,} == 'y' ]; then
  savecommit=$(git log --oneline | grep -n autosave | grep -v HEAD | head -n $saveno | tail -n1 | sed -E 's/[0-9]*:([0-9a-f]*) .*/\1/')
  echo
  echo
  git reset --hard $savecommit &>/dev/null
  echo " Rolled back to $ddate."
fi
echo