#!/bin/bash




ORIG_HTML=$1
LINE_BEGIN=$2
DIR_FOR_LINKFILES2=`echo ${ORIG_HTML} | sed 's/utf\-8//g;s/\.html//g'`
DIR_FOR_LINKFILES="..\\file_softlinks\\""${DIR_FOR_LINKFILES2}""_softlinks\\"
HTML_USING_MSLINK="../file_softlinks/""${ORIG_HTML}"
WGET_TMP_FILE="tmp.html"
MKLINK_TMP_FILE="tmp.txt"

echo_n_left_spaces()
{
   local CC=0
   while [ ${CC} -lt $1 ] ; do

      echo -n " "

      let CC=CC+1
   done

}

blink_msg()
{
   echo -n -e "\e[01m\e[5m$1\e[0m"
}
## Error to warning with blink
function bred(){
    echo -e "\033[31m\033[01m\033[05m[ $1 ]\033[0m"
}

## Error to warning with blink
function byellow(){
    echo -e "\033[33m\033[01m\033[05m[ $1 ]\033[0m"
}



sound_msg()
{
   echo -n $1
   echo -n -e "\a"
}

greenmsg()
{
	echo -n -e  "\e[32m$1\e[0m"
}
redmsg()
{
	echo -n -e  "\e[31m$1\e[0m"
}
boldmsg()
{
	echo -n -e  "\e[1m$1\e[0m"
}


# Shared functions for RosBE-Unix components
# Part of RosBE for Unix-based Operating Systems
# Copyright 2009 Colin Finck <mail@colinfinck.de>
#
# Released under GNU GPL v2 or any later version.

# Print a message in a bold font
#  Parameter 1: The message
#  Parameter 2: Optional additional parameters for "echo"
boldmsg2()
{
	echo -n -e $2 "\e[1m$1\e[0m"
}

# Print a message in green color
#  Parameter 1: The message
#  Parameter 2: Optional additional parameters for "echo"
greenmsg2()
{
	echo -n -e $2 "\e[32m$1\e[0m"
}

# Print a message in red color
#  Parameter 1: The message
#  Parameter 2: Optional additional parameters for "echo"
redmsg2()
{
	echo -n -e $2 "\e[31m$1\e[0m"
}
bluemsg2()
{
	echo -n -e $2 "\e[34m$1\e[0m"
}
bluemsg()
{
	echo -e $2 "\e[34m$1\e[0m"
}

result_check2()
{
	if [ $? -ne 0 ]; then
		redmsg "$1 FAILED"

		echo "Aborted!"
		exit 1
	else
		greenmsg "$1 OK"
	fi
}

result_check()
{
	if [ $? -ne 0 ]; then
		redmsg "FAILED"

		echo "Aborted!"
		exit 1
	else
		greenmsg "OK"
	fi
}




test()
{
while [ true ] ; do
sound_msg hi
#blink_msg test
byellow test
greenmsg no
redmsg   yes
boldmsg  bold
sleep    2
done
}


if [ X"${ORIG_HTML}" = X"" ] ; then 
  echo "Usage: ./softlinks_gen.sh   ORIG_HTML   [LINE_BEGIN]  "
  exit
fi
if [ X"${LINE_BEGIN}" = X"" ] ; then 
  LINE_BEGIN=1
fi


USING_SLASH=0
USING_BACKSLASH=0
VAR="\\\\"
#      
#check slash style 
#
for i in `cat ${ORIG_HTML} | grep -n "/\[" | awk -F ":" '{print $1}'` ; do
      let USING_SLASH+=1
done
for i in `cat ${ORIG_HTML} | grep -n "${VAR}\[" | awk -F ":" '{print $1}'` ; do
      let USING_BACKSLASH+=1
done
echo "Found ${USING_SLASH} /[ s AND ${USING_BACKSLASH} \\[ s"
if [ ${USING_SLASH} -gt 0 ] && [ ${USING_BACKSLASH} -gt 0  ] ; then
     echo "IT IS BAD THAT YOU ARE USING SLASH AND BACKSLASH STYLE IN ONE SAME FILE.exit."
     exit
elif [ ${USING_SLASH} -gt 0 ] ; then
      # deal with entry using slash
     COMMAND="`cat ${ORIG_HTML} | grep -n \"/\[\" | awk -F \":\" '{print $1}'`"
elif [ ${USING_BACKSLASH} -gt 0  ] ; then
      # deal with entry using backslash
     COMMAND="`cat ${ORIG_HTML} | grep -n \"${VAR}\[\" | awk -F \":\" '{print $1}'`"
else
     echo "Nothing to do, exit."
     exit
fi

#      
#check where we should begin
#      
TOTAL=`cat ${ORIG_HTML} | wc -l`
let NUM=LINE_BEGIN
#echo "begin from line $NUM"

ALREADY_DONE=0
if [ -e "${HTML_USING_MSLINK}" ] ; then
    ALREADY_DONE=`wc -l "${HTML_USING_MSLINK}" | awk '{print $1}'`
    echo "The HTML to be generated already finished ${ALREADY_DONE} lines."
else
    echo "${HTML_USING_MSLINK} doesn't exist, to create it and exit."
    touch "${HTML_USING_MSLINK}"
    exit
fi

ALREADY_DONE_NEXT=0
let ALREADY_DONE_NEXT=ALREADY_DONE+1
if [ $NUM -lt ${ALREADY_DONE_NEXT} ] ; then
    echo "Please delete useless lines in the generating HTML first! exiting...:"
    echo "    REQUESTED: ${NUM} < ${ALREADY_DONE} ALREADY DONE + 1."
    exit
elif [ $NUM -gt ${ALREADY_DONE_NEXT} ] ; then
    echo "You are specifying begin line number out of range! to exit:"
    echo "    REQUESTED: ${NUM} > ${ALREADY_DONE} ALREADY DONE + 1."
    exit
else
    echo "Well, the beginning line number is fine:"
    echo "    REQUESTED: ${NUM} = ${ALREADY_DONE} ALREADY DONE + 1."
fi



#      
# do it.
#      
for i in ${COMMAND} ; do
      if [ $NUM -gt $i ] ; then
          continue
      fi

      if [ $NUM -lt $i ] ; then
                 print_end=`expr $i - 1`
                 cat "${ORIG_HTML}" | sed -n ''$NUM','$print_end' p'    >>    "${HTML_USING_MSLINK}"
                 amount=`expr $print_end - $NUM`
                 amount=`expr $amount + 1`
                 let NUM+=$amount
      fi
      
     # handle line $i 
     #
     echo ""
     CUR_LINE=`cat ${ORIG_HTML}  | sed -n ''$NUM','$NUM' p'  `
     # handle a entry
     ENTRY_LINE=`echo "${CUR_LINE}" | grep -e "<li>"`
     # try to find "book" name and its file's full path
     FULL_PATH=`echo ${ENTRY_LINE} | sed 's/^\(.*\)href=\"\(.*\)\">\(.*\)<\/[Aa]><\/li>.*$/\2/g' `
     FULL_PATH=`echo ${FULL_PATH}`  # to trim the spaces 
                                    # but simply this will make multiple spaces among the string reduce to only one space. So it allows only 1 space in between.
     #echo "${FULL_PATH}"            # now "${FULL_PATH}" can be used
     FILE_NAME=`echo "${FULL_PATH}" | sed 's/^\(.*\)\/\([^\/][^\/]*\)$/\2/g'`
     # still at some places we use windows' backslashes, to check this
     #STR_CHECK=`echo "${FILE_NAME}" | grep -e '\\'`  # needs single quote here, still of problem in bash file
     VAR="\\\\"
     STR_CHECK=`echo "${FILE_NAME}" | grep -e "${VAR}"`  # needs this method
     if [ X"${STR_CHECK}" != X"" ] ; then
          FILE_NAME=`echo "${FILE_NAME}" | sed 's/^\(.*\)\\\\\([^\\\\][^\\\\]*\)$/\2/g'`  
     fi
     # for checking existance
     FULL_PATH_NO_PROTOCOL=`echo  "${FULL_PATH}" | sed 's/\(.*\):\/\/\(.*\)/\2/g'`
     #./check_existance.bat "${FULL_PATH_NO_PROTOCOL}"  # placed below
     
     #check if it is English name
     #TODO: How about French name etc.?
     STR_LEFT=`echo "${FILE_NAME}" | sed -e 's/[a-zA-Z0-9]//g;s/[%&(),;=_\ \.]//g;s/\+//g;s/\-//g;s/\[//g;s/\]//g' -e "s/'//g" `
     if [ X"${STR_LEFT}" != X"" ] ; then
         LATIN_STR=`echo "${FILE_NAME}" | grep -e "\[[a-zA-Z]" -e "\[\]" -e "\[([a-zA-Z]"`
         if [ X"${LATIN_STR}" != X"" ] ; then
             echo "not English but still is Latin.."
         else
             echo "$NUM:Not English or Latin book, skipped: ${FILE_NAME} STRING LEFT: ${STR_LEFT}"
             cat "${ORIG_HTML}" | sed -n ''$NUM','$NUM' p'    >>    "${HTML_USING_MSLINK}"
             let NUM=NUM+1
             continue
         fi
     fi
     
     # Now the real job
     echo "${NUM}:TODO:${FILE_NAME}" 
                  #remove suffix
                  STR_TMP1=`echo "${FILE_NAME}" | sed 's/\(.*\)\.[^\.][^\.]*/\1/g'`
                  #echo "${STR_TMP1}"
                  
                  #remove parenthese
                  #STR_TMP2=`echo "${STR_TMP1}"  | sed 's/(.*)/\ /g'`
                  STR_TMP2=`echo "${STR_TMP1}"  | sed 's/([^)][^)]*)/\ /g'`
                  #echo "${STR_TMP2}"
                  
                  #(remove "by" in [])
                  STR_TMP3=`echo "${STR_TMP2}"  | sed 's/\[by[_\ ]/\[/g'`
                  #echo "${STR_TMP3}"
                  
                  #(remove "(auth.)" in [])
                  #STR_TMP32=`echo "${STR_TMP3}"  | sed 's/\[\(.*\)(auth\.)\(.*\)$/\[\1\_\2/g'`
                  #echo "${STR_TMP32}"

                  #extract that in [], remove []
                  STR_TMP4=`echo "${STR_TMP3}"  | sed 's/\[/\ /g;s/\]/\ /g'`
                  #echo "${STR_TMP4}"
                  
                  #underline changed to space.  Also '&'';' changed to space.
                  STR_TMP5=`echo "${STR_TMP4}"  | sed 's/_/\ /g;s/[&;]/\ /g'`
                  #echo "${STR_TMP5}"
       
                  LIBGEN_SEARCH_KEYWORDS=""
                  LIBGEN_SEARCH_STR=""           
                  for word in `echo  "${STR_TMP5}" | awk '{for(i=1;i<=NF;i++) print $i;}'` ; do
                      if [ X"${LIBGEN_SEARCH_KEYWORDS}" == X"" ] ; then
                          LIBGEN_SEARCH_KEYWORDS="$word"
                      else
                          LIBGEN_SEARCH_KEYWORDS="${LIBGEN_SEARCH_KEYWORDS}""+""$word"
                      fi
                  done
                  LIBGEN_SEARCH_STR="http://gen.lib.rus.ec/search.php?req=""${LIBGEN_SEARCH_KEYWORDS}""&lg_topic=libgen&open=0&view=simple&res=100&phrase=0&column=def"
                  byellow ${LIBGEN_SEARCH_STR}#echo ${LIBGEN_SEARCH_STR}
                  #TEST_LIBGEN_SEARCH_STR="http://gen.lib.rus.ec/search.php?req=cohen+tannoudji+atom+and+photon&lg_topic=libgen&open=0&view=simple&res=100&phrase=0&column=def"
                  #wget -O ${WGET_TMP_FILE} "${TEST_LIBGEN_SEARCH_STR}"       
                  wget -O ${WGET_TMP_FILE} "${LIBGEN_SEARCH_STR}"       
                  SEARCH_RESULT=`grep -n -e "<a href=.*id=[0-9]*>.*"  ${WGET_TMP_FILE}   | sed 's/\(.*\)id=[0-9]*>\(.[^<]*\)<.*/\2/g'  | sed 's/^\(.*\)[\ ][\ ]*$/\1/g'`
                  SEARCH_RESULT_WITH_LINENO=`echo  "${SEARCH_RESULT}" |   grep -n ".*"`
                  byellow "${SEARCH_RESULT_WITH_LINENO}"
                  
                  RESULT_NUM=`echo "${SEARCH_RESULT}"  | wc -l`
                  byellow "There are ${RESULT_NUM} results."
                  #select one and reconstruct the file name combination
                  #RIGHT_BRACKET=`echo "${FILE_NAME} | grep "\]"`       #some e-book name lacks of ']' for the author name is too long.
                  SUFFIX=""
                  if ! [ X"${STR_TMP1}" == X"${FILE_NAME}" ] ; then
                       SUFFIX=`echo "${FILE_NAME}" | sed 's/^\(.*\)\(\.[^\.][^\.]*\)$/\2/g'`
                  fi
                  MARK=""
                  if ! [ X"${STR_TMP2}" == X"${STR_TMP1}"  ] ; then
                       MARK=`echo "${STR_TMP1}" | sed 's/^\(.*\)(\(.*\))$/(\2)/g'`
                  fi
                  AUTHOR=`echo "${STR_TMP2}" | sed 's/^\[\(.*\)\].*$/\[\1\]/g;'`
                  
                  if [ ${RESULT_NUM} -eq 1 ] ; then
                      UNDERLINED_NAME=`echo "${SEARCH_RESULT}" | sed 's/\ /_/g'`
                      MSLINK_NAME="${AUTHOR}""${UNDERLINED_NAME}""${MARK}""${SUFFIX}"
                      echo "Is this name that you want?OR to copy(1/y/n/c) :${MSLINK_NAME}"
                      read a
                      if [ X"$a" == X"y" ] || [ X"$a" == X"yes" ]  || [ X"$a" == X"1" ] ; then
                          #fall through  to do the job
                          echo "Well, I will do the job .."
                      elif [ X"$a" == X"c" ] || [ X"$a" == X"copy" ] ; then     # the zero search result seems to show 1 entry.
                          echo "Well, I will replicate .."
                          cat "${ORIG_HTML}" | sed -n ''$NUM','$NUM' p'    >>    "${HTML_USING_MSLINK}"
                          let NUM=NUM+1
                          continue
                      else
                          echo "You are not accepting any name that is possible, maybe you want to fix it manually,exiting..."
                          exit
                      fi
                  else
                      echo "Which one of the names do you want to select? Please input:"
                      while [ true ] ; do
                          read b
                          if [ $b -gt 0 ] && ! [ $b -gt ${RESULT_NUM} ] ; then
                              UNDERLINED_NAME=`echo "${SEARCH_RESULT}" | sed -n ''$b','$b' p' | sed 's/\ /_/g'`
                              MSLINK_NAME="${AUTHOR}""${UNDERLINED_NAME}""${MARK}""${SUFFIX}"
                              #echo "Is this name that you want?(y/n) :${MSLINK_NAME}"
                              #read c
                              #if [ X"$c" == X"y" ] || [ X"$c" == X"yes" ] ; then
                              #     #fall through to break and do the job
                              #     echo "Well, I will do the job .."
                              #else
                              #     echo "You are not accepting any name that is possible, maybe you want to fix it manually,exiting..."
                              #     exit
                              #fi
                              
                              break
                          else
                              echo "Your input number is out of range! Input again:"
                          fi
                      done
                  fi
                                    

     # last check                  
     if [ X"${MSLINK_NAME}" == X"" ] ; then
         echo "There is problem with link name:${MSLINK_NAME}, exiting"
         exit
     fi
     str_len=`expr length "${MSLINK_NAME}"`
     if [ ${str_len} -gt 150 ] ; then
         echo "A long name? length: ${str_len}"
     fi
     if [ ${str_len} -gt 190 ] ; then
         echo "The name to use is too long, trying to cut some words..."
         TRUNCATED_STR=${MSLINK_NAME:0:180}
         MSLINK_NAME="${TRUNCATED_STR}""${SUFFIX}"
         echo "truncation finished: ${MSLINK_NAME}"
         #exit
     fi
     # still the name cannot have special symbols inside, or it will be truncated
     # Windows doesn't allow \ / : * " ? < >  |
     MSLINK_NAME=`echo "${MSLINK_NAME}" | sed 's/[:\*\"<>\?\/]/\-/g'`   # assume the name has not a '\'
     # The .bat reckons the ',' ';' '&' as separator if the name is not in double quotes, but I have problem in calling .bat using double quotes under Cygwin.
     MSLINK_NAME=`echo "${MSLINK_NAME}" | sed 's/[,;&]/\-/g'`
     # After so many substitutions, especially for complex string case, the above name maybe  got ' ' left, remove them again.
     MSLINK_NAME=`echo "${MSLINK_NAME}" | sed 's/\ /_/g'`
     
     # check existance and only symbol-link it using selected name
     #    This met problem when the original book name has a ',' inside.
     #./mklink_if_exist.bat   "${FULL_PATH_NO_PROTOCOL}"   "${MSLINK_NAME}"  "${DIR_FOR_LINKFILES}"   #the name of the directory this .bat lies in cannot use '('')' etc.
     #    I have to deal with many double quotes.     
     #PARAMETERS="test.bat \"${FULL_PATH_NO_PROTOCOL}\" \"${MSLINK_NAME}\" \"${DIR_FOR_LINKFILES}\" "
     PARAMETERS="mklink_if_exist.bat \"${FULL_PATH_NO_PROTOCOL}\" \"${MSLINK_NAME}\" \"${DIR_FOR_LINKFILES}\" "
     cmd /C "$PARAMETERS"

     
     if  ! [ -e ${MKLINK_TMP_FILE} ] ; then
         echo "I don't find the file recording mslink .bat's result, exit and check it!"
         exit
     else
         #echo "TODO"       >>       "${HTML_USING_MSLINK}"
         RESULT_STRING2=`cat ${MKLINK_TMP_FILE}`
         RESULT_STRING=`echo -n ${RESULT_STRING2}`
         if   [ X"${RESULT_STRING:0:4}" == X"OKOK" ] ; then
             # reconstruct the HTML
             NEW_ENTRY_LINE=`echo "${ENTRY_LINE}" | sed 's/^\(.*\)href=\(.*\)">\(.*\)<\/[aA]>\(.*\)$/\1href=\2">'${MSLINK_NAME}'<\/A>\4/g'`
             echo "${NEW_ENTRY_LINE}"     >>       "${HTML_USING_MSLINK}"
             greenmsg "link name ok using : $MSLINK_NAME"
             echo ""
             greenmsg "---------------------------------"
             echo ""
             sleep 2
         elif [ X"${RESULT_STRING:0:4}" == X"FAIL" ] ; then
             echo "FAIL"       >>       "${HTML_USING_MSLINK}"
             redmsg "MSLINK FAILED, maybe you want to do it manually, exiting."
             exit
         else
             echo "UNKNOWN ERROR"       >>       "${HTML_USING_MSLINK}"
             redmsg "Why? I can't find out the MSLINK result OK or FAIL, I found first 4 chars :${RESULT_STRING:0:4} check it! exiting."
             exit
         fi
         
         rm -f ${MKLINK_TMP_FILE}
     fi
     
     
      
      
      let NUM+=1
done

while ! [ $NUM -gt $TOTAL ] ; do
                 cat "${ORIG_HTML}" | sed -n ''$NUM','$TOTAL' p'    >>    "${HTML_USING_MSLINK}"
                 amount=`expr $TOTAL - $NUM`
                 amount=`expr $amount + 1`
                 let NUM+=$amount
done

exit
