#!/usr/bin/tcsh -f

# fload.csh
#   This to be used manually in conjunction with ~/wi-awb/wi.csh 
#    After the XTerm window opens, you can run f from another window and it will pop up a web browser with  
#    the Internet Archive URLs loaded from the most recent run of wi.csh


set WI_PATH="/home/pepper/wi-awb/"   # customize this path (w/trailing slash)

set AWK="/usr/local/bin/gawk"
set SED="/bin/sed"
set WGET="/usr/bin/wget"
set CP="/bin/cp"
set LS="/bin/ls"
set RM="/bin/rm"
set MV="/bin/mv"
set MKDIR="/bin/mkdir"
set CHMOD="/bin/chmod"
set DATE="/bin/date"
set GREP="/bin/grep"
set TAIL="/usr/bin/tail"
set SLEEP="/bin/sleep"
set SORT="/usr/bin/sort"
set UNIQ="/usr/bin/uniq"
set CAT="/bin/cat"
set GETOPT="/usr/bin/getopt"
set XTERM="/bin/xterm" # This will startup faster if X is running in a separate window:
                         # setenv DISPLAY :0.0
                         # X -multiwindow

set BROWSER="/usr/bin/firefox"  # -> file symlink to the Windows executable

# alias LSD $AWK" -lreaddir 'BEGIN { FS = "'"'"/"'"'" } { if("'$3'"=="'"'"d"'"'") {print "'$2'"} }'"
alias LSF $AWK" -lreaddir 'BEGIN { FS = "'"'"/"'"'" } { if("'$3'"=="'"'"f"'"'") {print "'$2'"} }'"

setenv DISPLAY :0.0
setenv LANG en_US.UTF-8
setenv LC_COLLATE en_US.UTF-8

# Program can be called two ways.
# Method "location":
#  f [no argument] - loads most recent temp directory
#  f 1             - loads most recent -1
#  f 2             - loads most recent -2
# Method "datadir":
#  f -d wi-awb-1108105920   - load temp directory by this name

set offset = 0
set option = 0

source "$WI_PATH""getoptfload.csh"

if("$project" == "") then # Use project.cfg -> default.id
    set project = `$AWK '{if($0 ~ /^default[.]id/) {split($0,a,/[ ]{0,10}[=][ ]{0,10}/); print a[2]; i++; exit} }END{if(i == 0) print "unknown"}' "$WI_PATH""project.cfg"`
    if("$project" == "unknown") then
      echo "Unknown default project. Set default.id in project.cfg" > /dev/stderr
      exit
    endif            
endif
set projectdata = `$AWK -v id="$project" '{re = "^" id "[.]data"; if($0 ~ re) {split($0,a,/[ ]{0,10}[=][ ]{0,10}/); print a[2]; i++; exit} }END{if(i == 0 || i > 1 ) print "unknown"}' "$WI_PATH""project.cfg" `
set projectmeta = `$AWK -v id="$project" '{re = "^" id "[.]meta"; if($0 ~ re) {split($0,a,/[ ]{0,10}[=][ ]{0,10}/); print a[2]; i++; exit} }END{if(i == 0 || i > 1 ) print "unknown"}' "$WI_PATH""project.cfg" `

if( "$projectdata" == "unknown" || "$projectmeta" == "unknown" ) then
  echo "Unknown project data or meta." > /dev/stderr
  exit
endif

set type = `$AWK -v t="$dataid" 'BEGIN{if(t ~ /^[0-9]{1}$/) {print "location"; exit}; if(t ~ /wi-awb/) {print "datadir"; exit}; print "unknown"}'`

if ( "$type" == "datadir" ) then
  set WI_TEMP = "$projectdata""$dataid""/"
  set option = 2
else if( "$type" == "location" ) then
  if ("$dataid" == 0) then
    set offset = 0
    set option = 0
  else
    if("$dataid" == "1") then
      set offset = 1
      set option = 0
    else if("$dataid" == "2") then
      set offset = 0
      set option = 2
    else
      set offset = 0
      set option = 0
    endif
  endif
  # Create temp directory string 
  set tcount = `$AWK -lreaddir 'BEGIN { FS ="/" } { if($3 == "d" && $2 !~/^[.]{1,2}$/) {print $2} }' "$projectdata" | "$AWK" -v i=0 '{i++}END{print i}'` 
  # List all directories, filter out "." and ".." sort chronologically, pick the last one (minus any offset)
  set stamp =  `$AWK -lreaddir 'BEGIN { FS ="/" } { if($3 == "d" && $2 !~/^[.]{1,2}$/) {print $2} }' "$projectdata" | "$SORT" | "$AWK" -v o="$offset" -v n="$tcount" '{ if(NR == (n - o)) {c = split($0,a,"/"); print a[c]}}'` 
  set WI_TEMP = "$projectdata""$stamp""/"
endif

echo "$WI_TEMP" > /dev/stderr

if ( ! -e "$WI_TEMP" ) then 
  echo "Unable to find temp directory ""$WI_TEMP" > /dev/stderr
  goto myend
endif

#If cntrl-c interrupt, clean up temporary files - go to the myend: tag
onintr myend

  # Load Browser: Wikipedia article 
   set wpurl = `$AWK '{print $0}' "$WI_TEMP"tmpU`
   echo "$wpurl" > "$WI_TEMP""k.urls"

   # Load Browser: existing searches in the wikisource file

    if("$offset" == 1) then # refresh tmpW (wiki source) with older edition
      $WGET -q -O "$WI_TEMP"tmpW "$wpurl"
    endif

    if("$option" == 0) then # load URLs from wikisource and IA 

      if("$offset" == 1 || "$offset" == 0) then # 
        source "$WI_PATH""getiaurl.csh"         # Get URLs from tmpW

        # Load Browser: proposed searches (tmpO files) sorted in same order at bottom of article.txt
        foreach iatmpo (`LSF "$WI_TEMP" | "$GREP" tmpO | "$SORT" -n -t "@" -k4`)

         # Only load the tmpO URLs which have an entry in ia-results (which had URLs with duplicate hit counts+names removed)
          if(`$AWK -v s="$iatmpo" '{if(patsplit($0,a,s"$")) {print 1; exit}}' "$WI_TEMP"ia-results` == 1) then
            set iaurl = `$GREP -oE 'archive.+' "$WI_TEMP""$iatmpo" | $AWK '{gsub(/'\''/,"%27",$1); print $1}'`
            echo "Firefox (new): ""$iaurl"
            set iaurl = `$AWK -v url="$iaurl" 'BEGIN{gsub("archive.org/search.php","balbach.net/cgi-bin/iacs.awk",url); print url}'`
#            set iaurl = `$AWK -v url="$iaurl" 'BEGIN{gsub("archive.org/search.php","192.168.0.5:8080/",url); print url}'`
            echo "$iaurl" >> "$WI_TEMP""k.urls"
          endif
        end
      endif
    endif

    if("$option" == 2) then 
      # source "$WI_PATH""getiaurl.csh" # Get URLs from tmpW
     # Get IA URLs from choose.txt 
      set clength = `$AWK '/^[0-9]{1,2}[.]/{i++}END{print i}' "$WI_TEMP""choose.txt"`
      @ i = 0
      while($i < $clength)
        @ i++
        set choice = `$AWK -v c="$i" '/^[0-9]{1,2}[.]/{i++; if (i == c){split($0,a,"."); print a[1]}}' "$WI_TEMP""choose.txt"`
        foreach iatmpo (`LSF "$WI_TEMP" | "$GREP" tmpO | "$SORT" -n -t "@" -k4`)
          if("$choice" == `$AWK -v s="$iatmpo" 'BEGIN{split(s,a,"@"); print a[4]}'`) then
            set iaurl = `$GREP -oE 'archive.+' "$WI_TEMP""$iatmpo" | $AWK '{gsub(/'\''/,"%27",$1); print $1}'`      
            set iaurl = `$AWK -v url="$iaurl" 'BEGIN{gsub("archive.org/search.php","balbach.net/cgi-bin/iacs.awk",url); print url}'`
            echo "$iaurl" >> "$WI_TEMP""k.urls"
          endif
        end
      end
    endif

    if("$option" == 3) then # load cached html files. This doesn't work due to missing java etc.. something besides wget to save file?
      set clength = `$AWK '/^[0-9]{1,2}[.]/{i++}END{print i}' "$WI_TEMP""choose.txt"`
      @ i = 0
      while($i < $clength)
        @ i++
        set choice = `$AWK -v c="$i" '/^[0-9]{1,2}[.]/{i++; if (i == c){split($0,a,"."); print a[1]}}' "$WI_TEMP""choose.txt"`
        foreach iatmpo (`LSF "$WI_TEMP" | "$GREP" tmpO | "$SORT" -n -t "@" -k4`)
          if("$choice" == `$AWK -v s="$iatmpo" 'BEGIN{split(s,a,"@"); print a[4]}'`) then
            set myname = `$AWK -v s="$iatmpo" 'BEGIN{split(s,a,"@"); print a[2]}'`
            set mytype = `$AWK -v s="$iatmpo" 'BEGIN{split(s,a,"@"); print a[3]}'`
            set tmpi = `$AWK -v n="$myname" -v t="$mytype" 'BEGIN{printf("tmpI@%s@%s",n,t)}'`
            echo "file://localhost/c:/cygwin/""$WI_TEMP""$tmpi" >> "$WI_TEMP""k.urls"
          endif
        end
      end
    endif

    "$BROWSER" -P second -no-remote `$AWK '$0' "$WI_TEMP""k.urls"`

myend:
exit
