#############################################################################
#                                  wedi                                     #
#                                 wedi.sh                                   #
#                                                                           #
#############################################################################

#----------------------------------------------------------------------------
#Functions that control if WEDI_DATA_FILE, EDITOR and VISUAL are properly set
#----------------------------------------------------------------------------

isset_WEDI_data_file()
  {
   if [ -z "$WEDI_RC" ]
     then echo 'Variable WEDI_RC which is leading to wedi data file is not set. Please specify it and try again' ;
          echo 'Variable WEDI_RC which is leading to wedi data file is not set. Please specify it and try again' >&2;
          echo 'ERROR, script will be terminated !!!' ;
          echo 'ERROR, script will be terminated !!!' >&2;
          exit "2";
   fi
   if [ -d "$WEDI_RC" ]
     then echo 'Variable WEDI_RC which is leading to wedi data file is set as a directory. Please specify file and try again';
          echo 'Variable WEDI_RC which is leading to wedi data file is set as a directory. Please specify file and try again' >&2;
          echo 'ERROR, script will be terminated !!!'
          echo 'ERROR, script will be terminated !!!' >&2
          exit "1";
   fi
   if [ -e "$WEDI_RC" ]
     then true;
     else echo 'Variable WEDI_RC which is leading to wedi data file leads to file that does not exist. Please specify that file and try again';
          echo 'Variable WEDI_RC which is leading to wedi data file leads to file that does not exist. Please specify that file and try again' >&2;
          echo 'ERROR, script will be terminated !!!'
          echo 'ERROR, script will be terminated !!!' >&2
          exit "1";
   fi
   if [ -w "$WEDI_RC" ]
     then if [ -r "$WEDI_RC" ]
            then true;
        else echo 'Variable WEDI_RC which is leading to wedi data file contain path to non-readable or non-writable file. Please change parameters of that file and try again';
             echo 'Variable WEDI_RC which is leading to wedi data file contain path to non-readable or non-writable file. Please change parameters of that file and try again' >&2;
               echo 'ERROR, script will be terminated !!!'
               echo 'ERROR, script will be terminated !!!' >&2
              exit "1";
          fi
   fi
  }

isset_EDITOR()
  {
   if [ -z "$EDITOR" ]
     then if [ -z "$VISUAL" ]
            then echo 'Variable EDITOR nor VISUAL are set. Please specify atleast one and try again';
                 echo 'Variable EDITOR nor VISUAL are set. Please specify atleast one and try again' >&2;
            exit "1";
          fi
   fi
  }
  
#----------------------------------------------------------------------------
#       Functions for extraction FILE name nad PATH for any File
#----------------------------------------------------------------------------

param_to_file()
  {
   echo ${1##*/}
  }

param_to_path()
  {
   DELKA=$(( `echo "${#1}"` - `echo "${#2}"` ))

   if [ $DELKA -gt 0 ]
     then if [ `expr "$1" : '\.\/'` -eq 2 ]
             then CETSA="${1%$2*}"
                  echo `pwd`"${CETSA#\.*}"
             else echo ${1%$2*}
          fi
     else echo `pwd`"/"
   fi
  }

#----------------------------------------------------------------------------
#       Functions for opening file given
#----------------------------------------------------------------------------

open_file()
  {
   isset_EDITOR

   WEDI_FILE=`param_to_file "$1"`
   WEDI_PATH=`param_to_path "$1" "$WEDI_FILE"`
   HLEDANA_FRAZE=`echo "$WEDI_FILE    $WEDI_PATH    2"`
   grep -q -E "$HLEDANA_FRAZE""[^\/]{1,}[-]" $WEDI_RC
   POCET_ZAZNAMU=$?                        # 0 = nalezeno; 1 = nenalezeno
   if [ $POCET_ZAZNAMU = 0 ]
     then
       PUVODNI_ZAZNAM=`grep "$HLEDANA_FRAZE" $WEDI_RC`;
       POCET="$(echo $(( `echo ${PUVODNI_ZAZNAM##*-}` + 1 )) )";
       NOVY_ZAZNAM=`echo "$WEDI_FILE    $WEDI_PATH    "$(date +%Y-%m-%d-%s)'    -'$POCET`; # K datu pridana UNIX timestamp pro razeni
       ORIGINALNI_RADEK=`echo "$PUVODNI_ZAZNAM" | tail -1`
       PAMET=`grep -v "$ORIGINALNI_RADEK" $WEDI_RC`
       echo "$PAMET" > $WEDI_RC
       echo "$NOVY_ZAZNAM" >> $WEDI_RC
     else
       echo "$WEDI_FILE    $WEDI_PATH    "$(date +%Y-%m-%d-%s)"    -1" >> $WEDI_RC;    # Delimiter '-' used because of POSIX sort, not as value below zero
   fi

   if [ -z "$EDITOR" ]
     then $VISUAL "$1"
     else $EDITOR "$1"
   fi

   if [ $? -ne 0 ]
     then exit $?
   fi
}

#----------------------------------------------------------------------------
#                         EXEC PART
#----------------------------------------------------------------------------

isset_WEDI_data_file

if [ -z "$1" ]; then ARG_1='./'; else ARG_1="$1"; fi
if [ -z "$2" ]; then ARG_2='./'; else ARG_2="$2"; fi
if [ -z "$3" ]; then ARG_3='./'; else ARG_3="$3"; fi

if [ "$1" = "." ]; then ARG_1='./'; fi
if [ "$2" = "." ]; then ARG_2='./'; fi
if [ "$3" = "." ]; then ARG_3='./'; fi

# NEVER TOUCH THE RUNNING SYSTEM :o)
# BEGIN

if [ `echo $ARG_1 | head -c 1` != '-' ]                # kontrola ze to neni prepinac
  then if [ `echo $ARG_1 | tail -c 2` != '/' ]            # pokud se nejedna o slozku
         then open_file "$ARG_1";                    # otevreme
         else WEDI_FILE=`param_to_file "$ARG_1"`;            # jinak hledáme, zda-li už byl soubor otevřen pomocí WEDI
              WEDI_PATH=`param_to_path "$ARG_1" "$WEDI_FILE"`;
              HLEDANA_FRAZE=`echo "$WEDI_PATH    2"`

              grep -q -E "$HLEDANA_FRAZE""[^\/]{1,}[-]" $WEDI_RC
              POCET_ZAZNAMU=$?;                        # 0 = nalezeno; 1 = nenalezeno;
              if [ $POCET_ZAZNAMU = 0 ]
                then
                     sort -t $'\t' -k 3.3r -o $WEDI_RC $WEDI_RC
                     HLEDANA_FRAZE=`echo "$WEDI_PATH    2"`
                     ZAZNAMY=`grep -h "$HLEDANA_FRAZE" $WEDI_RC | head -n 1`
                     WEDI_PATH=${ZAZNAMY%`echo '    '`*}
                     WEDI_PATH=${WEDI_PATH%`echo '    '`*}
                     WEDI_PATH=${WEDI_PATH#*`echo '    '`}
                     WEDI_FILE=${ZAZNAMY%%`echo '    '`*}
                     WEDI_PATH=$WEDI_PATH$WEDI_FILE
                     open_file "$WEDI_PATH"
                else echo 'In selected directory was not edited any file with WEDI. Please specify different directory and try again';
                     echo 'In selected directory was not edited any file with WEDI. Please specify different directory and try again' >&2;
                     echo 'ERROR, script will be terminated !!!'
                     echo 'ERROR, script will be terminated !!!' >&2
                     exit 1;
              fi
       fi
fi

if [ `echo $ARG_1 | head -c 2` = '-m' ]
         then if [ `echo $ARG_2 | tail -c 2` != '/' ]
                then echo 'Selected path is not a directory. Please use / at the end of directories.';
                     echo 'Selected path is not a directory. Please use / at the end of directories.' >&2;
                     echo 'ERROR, script will be terminated !!!'
                     echo 'ERROR, script will be terminated !!!' >&2
                     exit 1;
                else WEDI_FILE=`param_to_file "$ARG_2"`;
                     WEDI_PATH=`param_to_path "$ARG_2" "$WEDI_FILE"`;
                     HLEDANA_FRAZE=`echo "    $WEDI_PATH"`

                     grep -q -E "$HLEDANA_FRAZE""[^\/]{1,}[-]" $WEDI_RC

                     POCET_ZAZNAMU=$?;                        # 0 = nalezeno; 1 = nenalezeno;
                     if [ $POCET_ZAZNAMU = 0 ]
                       then
                        sort -t $'\t' -k 4n -o $WEDI_RC $WEDI_RC
                            HLEDANA_FRAZE=`echo "    $WEDI_PATH"`
                            ZAZNAMY=`grep -E "$HLEDANA_FRAZE""[^\/]{1,}[-]" $WEDI_RC | head -n 1`
                        WEDI_PATH=${ZAZNAMY%`echo '    '`*}
                        WEDI_PATH=${WEDI_PATH%`echo '    '`*}
                        WEDI_PATH=${WEDI_PATH#*`echo '    '`}
                        WEDI_FILE=${ZAZNAMY%%`echo '    '`*}
                        WEDI_PATH="$WEDI_PATH$WEDI_FILE"
                        open_file "$WEDI_PATH"

              # OPTIONAL FUNCTION - WRITE ERROR WHEN NO FILE WAS EDITED WITH WEDI IN THAT DIRECTORY
                      #else echo 'In selected directory was not edited any file with WEDI. Please specify different directory and try again';
                      #     echo 'ERROR, script will be terminated !!!'
                      #     exit 1;
                     fi
              fi
fi

if [ `echo $ARG_1 | head -c 2` = '-l' ]
         then if [ `echo $ARG_2 | tail -c 2` != '/' ]
                then echo 'Selected path is not a directory. Please use / at the end of directories.';
                     echo 'Selected path is not a directory. Please use / at the end of directories.' >&2;
                     echo 'ERROR, script will be terminated !!!'
                     echo 'ERROR, script will be terminated !!!' >&2
                     exit 1;
                else WEDI_FILE=`param_to_file "$ARG_2"`;
                     WEDI_PATH=`param_to_path "$ARG_2" "$WEDI_FILE"`;
                     HLEDANA_FRAZE=`echo "    $WEDI_PATH"`

                     grep -q -E "$HLEDANA_FRAZE""[^\/]{1,}[-]" $WEDI_RC
                     NENALEZENO=$?;                        # 0 = nalezeno; 1 = nenalezeno;
                     if [ $NENALEZENO = 0 ]
                       then grep -E "$HLEDANA_FRAZE""[^\/]{1,}[-]" $WEDI_RC | cut -f 1,1 | sort -k 1,1;
             #  OPTIONAL FUNCTION - WRITE ERROR WHEN NO FILE WAS EDITED WITH WEDI IN THAT DIRECTORY
                     #  else echo 'In selected directory was not edited any file with WEDI. Please specify different directory and try again';
                     #       echo 'ERROR, script will be terminated !!!'
                     #       exit 1;
                     fi
              fi
fi

if [ `echo $ARG_1 | head -c 2` = '-a' -o `echo $ARG_1 | head -c 2` = '-b' ]
         then if [ `echo $ARG_3 | tail -c 2` != '/' ]
                then echo 'Selected path is not a directory. Please use / at the end of directories.';
                     echo 'Selected path is not a directory. Please use / at the end of directories.' >&2;
                     echo 'ERROR, script will be terminated !!!'
                     echo 'ERROR, script will be terminated !!!' >&2
                     exit 1;
                else WEDI_FILE=`param_to_file "$ARG_3"`;
                     WEDI_PATH=`param_to_path "$ARG_3" "$WEDI_FILE"`;
                     HLEDANA_FRAZE=`echo "$WEDI_FILE    $WEDI_PATH    2"`
                     POCET_ZAZNAMU=`grep -c "$HLEDANA_FRAZE" $WEDI_RC`

             # OPTIONAL FUNCTION - WRITE ERROR WHEN NO FILE WAS EDITED WITH WEDI IN THAT DIRECTORY
                     #grep -q -E "$HLEDANA_FRAZE""[^\/]{1,}[-]" $WEDI_RC
                     #NENALEZENO=$?;                        # 0 = nalezeno; 1 = nenalezeno;
                     #if [ $NENALEZENO -ne 0 ]
                     #  then echo 'In selected directory was not edited any file with WEDI. Please specify different directory and try again';
                     #       echo 'ERROR, script will be terminated !!!'
                     #       exit 1;
                     #fi

                     if [ `echo $ARG_1 | head -c 2` = '-a' ]
                       then grep -h "$HLEDANA_FRAZE" $WEDI_RC | awk -v ARG2="$ARG_2" -F $'\t' '$3>=ARG2' | cut -f 1,1 | sort -k 1,1
                       else grep -h "$HLEDANA_FRAZE" $WEDI_RC | awk -v ARG2="$ARG_2" -F $'\t' '$3<=ARG2' | cut -f 1,1 | sort -k 1,1
             fi
              fi
fi

# END

#----------------------------------------------------------------------------
#                         DOCUMENTATION
#----------------------------------------------------------------------------
# STRUCTURE of WEDI_RC file
#    delimiter:    TAB, LF, '-'
#    reason:        TAB nor LF can be written in shell
#            '-' is used as numeric prefix. While value cannot be less then 1, '-' can be used in math operations.
#
#    content:
#        NAME_OF_FILE TAB PATH TAB DATE(YYYY-MM-DD-timestamp) TAB '-'VALUE LF
#
#----------------------------------------------------------------------------
#----------------------------------------------------------------------------
#                             HELP
#----------------------------------------------------------------------------
# what is this:
#    program WEDI is a wrapper. You select file, he asks $EDITOR or $VISUAL to opent it and it has memory
# run sequence:
#    wedi [ |-l|-m|-a|-b] [DATE] [PATH]
# options:
#    standard
#        wedi open the last file edited by wedi in current directory
#    [PATH]
#        wedi open file given or in case of directory the last edited with wedi in given path
#    -l [PATH]
#        wedi print list of files edited by wedi in given or actual directory
#    -m [PATH]
#        wedi open last file edited with wedi in given path or in actual directory
#    -a YYYY-MM-DD [PATH] | -b YYYY-MM-DD [PATH]
#        wedi print list of files edited by wedi in given or actual directory (-b before | -a after) given date, include this date.
#----------------------------------------------------------------------------
# variables
#    $EDITOR
#        eviroment variable containing text editor. Either $EDITOR or $VISUAL must be set
#    $VISUAL
#        eviroment variable containing text editor
#    $WEDI_RC
#        absolute path to WEDI_DATA_FILE. This file is recomended to be not edited or changed, nor not-empty at first set.
#----------------------------------------------------------------------------
# WARNING
#    Theese mistakes will lead often to undefined behavior
#        PATH to file ending with '/'
#            directory is file of files. This leads often to edit structure of that directory !!!
#        PATH to directory NOT ending with '/'
#            instead `pwd` use `pwd`"/"
#        blank or special chars in PATH
#            use wedi 'PATH' instead of wedi PATH
#        $WEDI_RC is used by another program
#        $WEDI_RC contain data not generated by wedi itself
#        DATE is not in format YYYY-MM-DD or contain false date as 2015-46-35
#----------------------------------------------------------------------------
# Author
#    Michal Schorm
#    2015
#
#    created as university project
#    xschor02
#----------------------------------------------------------------------------