#!/usr/local/bin/perl
#
#  script name:   dir-join2
#  used from  :   /users/jgofs/htmlbin
#  taken from dir to allow user to select an object for join
#   Christine Hammond
#   September 8, 1997
#
# 24 Mar 16.  WJS
#       Version of this for GEOTRACES EPZT-specific OOserver
#      Get what we can from build-opt-env.pl, but not everything is in there.  However, I think
#      we can get the ones we need to get, at worst, a "non-optimal" display.  My bet is that the
#      web page that "calls" this routine will also be "non-optimal" and after a couple of file edits,
#      nobody will care/remember
#  9 Jul 08.  WJS
#       Version of this for port 8200 OOserver
#  January 18, 2000  rcg
#       "Hand edit" variables for use on default server as per CLH
#       instructions.  Then again latter in the day, per email.
#  mod: January 14, 2000 clh
#    same change as to 'dir' wherein all <pre> tags are better
#    switched off after any switch on, to enable LYNX to properly
#    align columns
#
#  mod: November 13, 1998 clh
#    assign variable refhost to be the Optionserver calling this prog
#    checks HTTP_REFERER on first pass, then, uses a default value
#    passes value of refhost on to next dir-join using QUERY_STRING
#


require "build-opt-env.pl";
# The 4 parameters below were hard-coded in the original.  Mapping these into build-opt-env.pl parameters
# with high hopes...  It is entirely possible that other strings in this program can be replaced by build-opt-env.pl
# parameters as well, but we are still in "touch as little as possible" mode
$jghome = $ENV{"JGOFSDIR"};
$office = $ENV{"DMONAME"};
$imagedir = $ENV{"BUTTONIMAGESDIR"};
$default_option_server = $ENV{"OPTIONSERVER"};

############ Customized values for this site ###################
# topdir is a dir concept.  In particular, it is NOT related to the jgofs root.  (I think it is
# related to the objects file directory tree).  The topdir here in this pseudo-dir may or may not
# be logically correlated with the topdir in the dir for this server
#$topdir="/jgofs/";
#$topdir="/globec/gb/";
$topdir="/persistent_objects/";
$test_port="8081";  #accesses from this port considered test environment
############ End of Custom values for this site ################
#
$dictionary=".remoteobjects";
$logentry=".log";
$dirspacer = "  ";
$jgroot=$jghome."/objects";
$test_env=($ENV{"SERVER_PORT"} == $test_port);
#
#
#
print "Content-type: text/html\n\n";
#
# strip the leading '//' from hostnames used by this script
#
if ("$infoserver" =~ /\/\//) {
  $infoserver=substr($infoserver,2);
}
#
# get name of this server from env of httpd
#
if ($ENV{'SERVER_NAME'}) {
   $fromhost = $ENV{'SERVER_NAME'};
   if ($ENV{'SERVER_PORT'}) {
      $p=$ENV{'SERVER_PORT'};
      if ($p != 80) {
         $fromhost .= ":".$p;
      }
   }
} else {
   $fromhost = "usjgofs.whoi.edu";
}

if ($fromhost =~ /\/\//) {
  $fromhost=substr($fromhost,2);
}
#
# Get referring host - Optionserver
#
#  if there is a QS, it is the referring host, having been sent
#  by a previous dir-join click - see printf lines sending the
#  directory categories display
#
if ($ENV{'QUERY_STRING'}) {
  $refhost = $ENV{'QUERY_STRING'};
#
# otherwise, check for an environment var which is present on
#   some but not all httpd environments.
#
} elsif ($ENV{'HTTP_REFERER'}) {
    $refhost = $ENV{'HTTP_REFERER'};
    if (index($refhost,"//") != -1) {
      $r = substr($refhost,7);
      $refhost = substr($r,0,index($r,'/'));
    }
} else {
#    Problem w/ "Change per CH email" action below is that $default_option_host is not defined in this
#    program or anywhere else I could find.  Presumably we don't get to this else block very often.  I
#    am changing it back.  Either way a bad link will get presented, but I'm assuming that an "almost" type
#    bad link is better than an empty file.  Besides, doing it my way removes the 2 "used only once" perl
#    diagnostics
####    #    $refhost="$default_option_server";  Change per CH email 2000/1/18
####        $refhost=$default_option_host;
    $refhost="$default_option_server";
}

#
if ($ENV{'PATH_INFO'}) {
   $arg = $ENV{'PATH_INFO'};
} else {
   $arg = $topdir;
}

$currentdir = $arg;

$curdir = $currentdir;
chop($curdir);

&display_data_entries;
&display_data_categories;

# -------------------------Subroutines----------------------------
# display_data_entries - display current directory for user,
#    display all customized headings, display all entries in
#    either log dictionary or remoteobjects dictionary. Special
#    case entry displayed at end - for non-JGOFS entries.
#
sub display_data_entries {

print "<title>$currentdir data directory page</title>\n";

chdir("$jgroot$currentdir");
#
# Always check for a file of HTML code to customizes whole system
#
print "<center>";
print "<font size=\"7\"><b>$office Data System</b></font>\n";
print "</center>";

#
# Check that there is some data to display (.remoteobjects or .log)
#

if (-r $dictionary || -r $logentry) {

   print "\n<H2>Directory of Data in $currentdir</H2>\n";
   print "<pre>\n";
   if (-r $logentry) {
      &readdct($logentry);
       print "\n</pre>";
   }

   if (-r $dictionary) {
     print "<pre><strong><em>Data              Investigator         Description and Documentation</em></strong>\n";
     print "<hr>\n";
     &readdct($dictionary);
   }
   print "<hr>\n</pre>";

}
#
# Special case for non-objects or almost-objects
#       *** commented out for dir-join2
#       *** because we cannot necessarily
#       *** join with 'almost-objects'
#
#   if (-r ".almost") {
#       print "<pre><hr>\n";
#       open(INFILE,".almost");
#       while (<INFILE>) {
#        print;
#       }
#       print "\n</pre>";
#   }

}

# ------------------------------------------
#  readdct - gets a dictionary entry from 'get_entry' routine,
#            prints it, using 'print_entry' routine
#
sub readdct{
   local($whichone) = pop(@_);
   local($ndx) = 0;

   open(INFILE,"$whichone") || die "Can't open input file: $!\n";

   while (&get_entry()) {
      &analyze_entry();
      &print_entry();
   }
   close(INFILE);
}

# -------------------------------------------
# get_entry - read the dictionary entry,
#             return false if no more entries
#
sub get_entry{
   local($i);
   local($true) = "1";
   local($false) = "0";

   @dictentry = "";

   if (eof(INFILE)) {
      $i = $false;
   } else {
      foreach $i (1,2,3) {
        $dictentry[$i] = <INFILE>;
        chop($dictentry[$i]);
      }
      $i = $true;
   }
}


# -------------------------------------------------------
# analyze_entry - populate the fields that are displayed,
#                 based on these rules governing entries:
##############################################################################
#  Rules
#   0. entries consist of 3 lines, as:
#
#      line 1    displayed_object_name=information
#      line 2    - PI_name
#      line 3    - [optional_info] description
#                ^Note: the carot indicates column 1 start
#
#   1. 3rd line contains a brief description of the data, which will
#      become the link to the documentation file.  Optionally, a URL
#      can be included, BEFORE the brief description and separated from it
#      by a space, to indicate a change from the system default documentation
#      scheme (see below).  Syntax for this optional_info is a URL (can omit
#      hostname, if local host) - only exception applies if documentation file
#      name is x.info, where x is displayed_object_name:  can end URL in '/'
#      after the path and omit the displayed_object_name.
#           For example, this .remoteobjects entry:
#      phys_params=//another_machine/pacific/cruise77/phys_params
#      - J.Investigator
#      - http://another_machine/jg/info/pacific/cruise77/
#           directs dir to another_machine's /jg/info script which will
#      read a file named 'phys_params.info' in the systems's objects/ tree
#      subdirectory names pacific/cruise77.
#
#   2. 2nd line contains the Investigator's name responsible for data
#
#   3. 1st line identifies an object name and some information required to
#      reach it, as:
#
#      displayed_object_name=information_for_hypertext_link
#
#      2 possible forms for syntax of right hand side are
#
#     i.     http:[host]/jg/serv/path/to/object.html0[Xsub-selectionsY]
#    ii.     //host/path/to/objectname[Xsub-selectionsY]
#
#        where [ and ] indicate an optional portion of the syntax,
#          X is a "(", then a comma-separated list of sub-selection parameters
#          Y is a ")", used to complete the list
##############################################################################
#
sub analyze_entry{
#
#  check that anything is written on 3rd line
#

 $descript = "";
# Commenting out next line since it is only reference to addjobtoinfo in this program
# addjobtoinfo is used in dir.  Presumably this program doesn't execute that portion of dir
#  $addobjtoinfo = "n";
 if (length($dictentry[3]) > 2) {
#
#  when supplied, the optional info-serving information is a complete URL
#
    if ($dictentry[3] =~ /http:\//) {
#
#  a space separates the info serving host and path from the description
#
       $ndx = index($dictentry[3]," ",2);
       $descript = substr($dictentry[3],$ndx+1);

    } else {

       $descript = substr($dictentry[3],2);
    }
 } else {
#
# no information provided on line
#
     $descript = "";
 }
#
# the PI name is on the 2nd line of a dictionary entry
#
 $PI="";
 if (length($dictentry[2]) > 2) {
    $PI=substr($dictentry[2],2);
 }

#
# 1st line has object=serving-host entry
#

 $URL4obj="";

 $dispobj=substr($dictentry[1],0,index($dictentry[1],"="));
 $rightside=substr($dictentry[1],(index($dictentry[1],"=")+1));

#
# the serving host is provided, strip off anything before it
#
  $ndx = index($rightside,"//");
  if ($ndx != -1) {
    $rightside = substr($rightside,$ndx+2);
    $haveserver = "y";
  } else {
    $haveserver = "";
  }

#
# enhancement to catch entries with subselections and htmlify them
#
 $subselections="";
 if ($rightside =~ /\/.+\(.+\)/ ) {
   $ndx = index($rightside,"(");
   $subselections=substr($rightside,$ndx+1,length($rightside)-$ndx-2);
   $rightside=substr($rightside,0,$ndx);
 }

#
# syntax of rightside can include full url: http:[hostname]/jg/serv/test.html0
#
 if ($rightside =~ /jg\/serv/) {
    if ($haveserver) {
      $URL4obj="$rightside";
    } else {
#
# might be form, http:/jg/serv/path/obj
#
      $ndx = index($rightside,"http:");
      if ($ndx != -1) {
         $rightside = substr($rightside,$ndx+5);
         $URL4obj="$fromhost"."$rightside";
      }
    }
#    $datastring="$URL4obj";
#    $URL4obj.="{dir="."$dirstring";
 } else {
#
# it is a pseudo-URL, with no serving process listed - insert /jg/serv
#

    $servhost=substr($rightside,0,index($rightside,"/",2));
    $fullobj=substr($rightside,index($rightside,"/",2));

    if ($servhost =~ /\/\//) {
       $servhost = substr($servhost,2);
    }
    $URL4obj="$servhost"."$fullobj".".html0";
 }

 if ($subselections) {
    $URL4obj.="?"."$subselections";
 }

}

# --------------------------------
# print_entry -  format the output
#
sub print_entry{
#
# print the object name as a hypertext link
#
   $URL4obj =~ s/\/jg\/serv//;
   printf("<a href=\"http://%s/jg/getobj2//%s\">%-18s</a>",
             $refhost, $URL4obj, $dispobj);
#
# print the PI name
#
   if ($PI) {
      printf("<b>%-20s</b>", $PI);
   } else {
      printf("%-20s", "  ");
   }
#
# finally, print description of the object
#
   print "$descript\n";

}


# --------------------------------
# display_data_categories - list all JGOFS categories of data
#   read subdirectories from topdir and down, displaying the
#   final element (tail) of the directory list.
#
sub display_data_categories {
#
# Always print the directory categories of data in the jgroot
#
print "<H2>$office Data Categories</H2>";
print "<H4>Go to the indicated category of data by clicking on its name</H4>\n";
print "<p><pre>\n";
#
# First, find all subdirectories in the given tree
#
$find_command="find $jgroot$topdir -type d";
if ( $test_env ) {
   $find_command .= " -follow";
}
$find_command .= " -print";
open(FIND,"$find_command | sort |");

$|=1;
while ($dir = <FIND>) {
  chop $dir;
#
# find all subdirectories containing 'objects' and the top of the tree
#
  if ($dir =~ /\/objects\// && $dir =~ /$topdir/) {
#
# the url pathitem for the link starts at $topdir
#
    $urldir = substr($dir,(rindex($dir,$topdir)));
#
# strip final '/' from $topdir (only one that has it), printf will insert it.
#
    if ($urldir eq $topdir) {
       $urldir = substr($topdir,0,(rindex($topdir,"/")));
    }
    @subdirs = split(/\//,$dir);
    foreach $diritem (@subdirs) {
     print $dirspacer;
    }
    @revlist = reverse(@subdirs);
#
# get tail of directory list - last item in array of directories
#
    $diritem = shift(@revlist);
#
# mark the current directory being displayed by an arrow
#   change nov.1998 clh - add QS of referring host to propogate OOhost
#
    if ($curdir eq $urldir) {
      if (defined($imagedir)) {
          printf "     <a href=\"http:/jg/dir-join2%s/?%s\">%s</a>    <img \
          src=\"%s/youhere.gif\">\n",$urldir,$refhost,$diritem,$imagedir;
      } else {
          printf "     <a href=\"http:/jg/dir-join2%s/?%s\">%s</a>    <-----\n",
                   $urldir,$refhost,$diritem;
      }
    } else {
       printf "     <a href=\"http:/jg/dir-join2%s/?%s\">%s</a>\n",$urldir,$refhost,$diritem;
    }
#
  }
}
close(FIND);
print "</pre>\n";
}
