#!/bin/bash
SESSIONSDIR=$HOME/.vim/sessions
VIMSERVERLIST=$(vim --serverlist)
if [[ $1 == "-h" ]]; then
  echo Usage: "$0 [-h] [-q] [-a]"
  echo Stores sessions of all open gvim instances to $SESSIONSDIR
  echo "If -q is given, quits the gvim instances (saving all open files with :wqa)"
  echo "If -a is given, quits the gvim instances (saving all open files with :wqa)"

elif [[ ${#VIMSERVERLIST} == 0 ]]; then
  echo "No vim sessions to save. Keeping old ones. (To remove them, clear $SESSIONSDIR)"
else
  if [[ $1 == "-q" || $2 == "-q" ]]; then
    AND_QUIT=':wqa'
  fi
  mkdir -p $SESSIONSDIR/backup/
  if [[ $1 == "-a" || $2 == "-a" ]]; then
    #Prevent overwriting because of same vimservername
    rename 's/session-/session-previous-/' $SESSIONSDIR/session-*
  else
    gzip $SESSIONSDIR/session-*
    mv -b -f $SESSIONSDIR/session-* $SESSIONSDIR/backup/
  fi

  for VIMSERVER in $VIMSERVERLIST; do
    #Need to close all tagbars, as the plugin's syntax generates errors on restore because the plugin is configured in .vimrc to only loaded when opening a tagbar (but does not load when restoring the session)
    vim --servername $VIMSERVER --remote-send ":tabdo TagbarClose:mks $SESSIONSDIR/session-$VIMSERVER${AND_QUIT}"
  done
fi
