#!/bin/sh

#----------------------------------------------------------------------
#
# $Id: installServers,v 1.8.2.8 2004/01/12 20:59:21 jimg Exp $
#
# Install servers in the local cgi-bin/ directory.
# 
#----------------------------------------------------------------------

# Figure out if -n works with echo. This little `if' was stolen from
# autoconf. 4/11/2001 jhrg.
if (echo "testing\c"; echo 1,2,3) | grep c >/dev/null; then
  # Stardent Vistra SVR4 grep lacks -e, says ghazi@caip.rutgers.edu.
  if (echo -n testing; echo 1,2,3) | sed s/-n/xn/ | grep xn >/dev/null; then
    ac_n= ac_c='
' ac_t='	'
  else
    ac_n=-n ac_c= ac_t=
  fi
else
  ac_n= ac_c='\c' ac_t=
fi

usage="$0: interactively prompt for information and install DODS servers.

Options: u <dir>: Remove the DODS servers from <dir>, prompts before
                  actually removing anything.
"

# Send registration email here.
Server_Registration_Email="support@unidata.ucar.edu, jgallagher@opendap.org"

unistDir=""			# If set, user wants to remove DODS :-(
files=""			# Files to (un)install
jgfiles=""                      # JGOFS Files to (un)install
server_list=""			# List of servers to install
register=""			# y or n; register this site/server.

# Additional files, server tools (not for a specific server). If you *change*
# the value of these variables be sure to change the text farther down that
# lists the files/dirs.
#
# Note: nph-dods is handled as special case, copied and perl path fixed.
# erd 2002/01/03
# Note: DODS_Cache.pm is handled as special case, copied and gzip path
# fixed, if needed.
# erd 2002/01/04
addFiles="DODS_Dispatch.pm DODS_Cache.pm FilterDirHTML.pm \
read_config.pm dods_logging.pm dods.rc \
asciival deflate usage www_int 
curl"

# HTTP, LWP, MIME no longer used. Replaced by libcurl. 2003/05/09 erd
#addDirs="HTML HTTP LWP MIME"
addDirs="HTML"

#-----
# Process the options
#-----
x=`getopt hu: "$@"`		# "$@" preserves quotes in the input
if [ $? != 0 ]			# $? is the exit status of 'getopt ...'
    then
    echo "${usage}"
    exit 2
fi

# set -- $x sets the shell positional params $1, $2, ... to the tokens in $x
# (which were put there by `getopt ...`. The eval preserves any quotes in $x.
eval set -- $x

for i in "$@"
  do
  case $i in
      -u) uninstDir=$2; shift 2;;
      -h) echo "$usage"; exit 0;;
	 # Add these back in if a non-interactive mode is needed. Needs work. 
	 # 5/21/2002 jhrg 
	 # -r) register="y"; shift 1;;
	 # -m) machine=$2; shift 2;;
      --) shift 1;;
  esac
done

#-----
# Handle the uninstall
#-----
if test -n "$uninstDir"
    then
    # Test that the directory is correct.
    if test ! -d $uninstDir
	then
	echo "The directory ($uninstDir) does not exist!"
	exit 1
    fi
    # cd and remove in a subshell
    (cd $uninstDir
	removeFiles=`ls *_das *_dds *_dods $addFiles DODS_STATISTICS 2>/dev/null`
	removeDirs=`ls -d $addDirs 2>/dev/null`
	echo $ac_n "Uninstalling the DODS servers in $uninstDir. Are you sure 
you want to delete the files:
$removeFiles
and the directories:
$removeDirs
in $uninstDir (y/n) [n]? "
	read yesNo
	if test -z "$yesNo"; then yesNo="n"; fi
	if test "${yesNo}" = "y" -o "${yesNo}" = "Y"
	    then
	    test -n "$removeFiles" && rm $removeFiles
	    test -n "$removeDirs" && rm -r $removeDirs
	    echo "DODS server uninstalled"
	    exit 0
	else
	    echo "Uninstall canceled"
	    exit 0
	    fi)
    exit 1			# If here, something broke in the subshell
fi   

#-----
# Handle the install
#-----

#-----
# Determine which servers are to be installed and check that
# executables exist.
#-----

echo \
"Once you've run this script, please read over the INSTALL-servers help file. 
Two or three minutes there may save you save you much time.

This script will need to know the full pathname of the directory where you 
would like to install the servers. If you need to look around on system, it
is probably a good idea to stop this, figure out that path and restart this
script. It won't hurt to stop the script later on, but you might save yourself
a little time. Similarly, you will need to know the pathnames of your web
daemon's access and error logs if you would like to turn on remote access to
DODS stats. This feature is entirely optional.

Tell me which DODS servers you would like to install. Find the server in the
menu below and type its corresponding number. If you want to install more than
one server, list their numbers separated by spaces. If you decide later to
install more servers, rerun this installer specifying the additional
server(s)
"

while test -z "$num_list"; do
    echo $ac_n \
"1 FreeForm
2 JGOFS
3 NetCDF
4 HDF 4
5 MatLab
6 Dsp

?"

    read num_list;

    #-----
    # Figure out which servers to install and provide some feedback to the
    # installer. 
    #-----
    echo $ac_n "Servers chosen:"
    for num in $num_list
    do
	echo $ac_n " "
	case $num in
	    1) server_list="$server_list ff"; echo $ac_n "FreeForm";;
	    2) server_list="$server_list jg"; echo $ac_n "JGOFS";;
	    3) server_list="$server_list nc"; echo $ac_n "NetCDF";;
	    4) server_list="$server_list hdf"; echo $ac_n "HDF-4";;
	    5) server_list="$server_list mat"; echo $ac_n "MatLab";;
	    6) server_list="$server_list dsp"; echo $ac_n "Dsp";;
	esac
    done
    echo; echo

    if test -z "$server_list"
    then
	echo \
"I did not understand your response. Example responses:
To install the FreeForm server, type 1; to install both the 
FreeForm and HDF servers, type 1 4
"
	num_list=
    fi
done

#-----
# Check on programs.
#-----
for server in $server_list
  do
  # echo "${server}"
  for file in ${server}_das ${server}_dds ${server}_dods
    do
    if test ! -f "${file}"
	then
	echo "Error: Required file ${file} (part of the $server) does not exist!
Check to see if you have downloaded and/or built all the needed files."
	exit 1
    else
	files="${files} ${file}"
    fi
  done

  #-----
  # Any nonstandard files?
  #-----
  if test "${server}" = "jg"
      then
      for usageFile in usage-jg
	do
	if test ! -f "${usageFile}"
	    then
	    echo "
Error: Required file ${usageFile} (part of the $server) does not exist!
Check to see if you have downloaded and/or built all the needed files."
	    exit 1
	else
	    files="${files} ${usageFile}"
	fi
      done
  fi

  # Treat some of the JGOFS files specially. Note that these are added to a 
  # different variable and are later installed in a different directory. 
  # 03/06/03 jhrg
  if test "${server}" = "jg"
      then
      for jgFile in def jgofs_objects_readme
	do
	if test ! -f "${jgFile}"
	    then
	    echo "
Error: Required file ${jgFile} (part of the $server) does not exist!
Check to see if you have downloaded and/or built all the needed files."
	    exit 1
	else
	    jgfiles="${jgfiles} ${jgFile}"
	fi
      done
  fi

done

#-----
# Find perl
#-----
echo $ac_n "Checking for perl..."
if test -n "$PERL"; then
    ac_cv_prog_PERL="$PERL" # Let the user override the test.
else
    IFS="${IFS= 	}"; ac_save_ifs="$IFS"; IFS=":"
    ac_dummy="$PATH"
    for ac_dir in $ac_dummy; do
	test -z "$ac_dir" && ac_dir=.
	if test -f $ac_dir/perl; then
	    ac_cv_prog_PERL="$ac_dir/perl"
	    break
	fi
    done
    IFS="$ac_save_ifs"
fi
PERL="$ac_cv_prog_PERL"
if test -n "$PERL"; then
    echo "  $PERL"
else
    echo $ac_n "Where is perl located on your system [e.g., /usr/bin/perl]? "
    read user_perl
    PERL="$user_perl"
fi

case "$PERL" in
    *perl)
	perl_ver=`$PERL -v 2>&1 | awk '/This is perl/ {print}'`
	perl_ver=`echo $perl_ver | sed 's/This is perl, [a-z ]*\([0-9._]*\).*/\1/'`
	perl_ver_main=`echo $perl_ver | sed 's/\([0-9]*\).*/\1/'`
	if test -n "$perl_ver" && test $perl_ver_main -ge 5
	    then
	    echo "I Found perl version ${perl_ver}, good."
	else
	    echo "I Found perl version ${perl_ver} but you must have 5.0 or newer."
	    exit 1
	fi
	;;
    *)
	echo "Perl 5.0 or newer is required to run these servers."
	exit 1
	;;
esac

echo

#-----
#
#-----
# echo "Where is the cgi-bin directory located on your"
# echo "system [e.g., /usr/local/apache/cgi-bin]?"

echo $ac_n \
"Where would you like the servers to be located on your system? This *must*
be a directory that your httpd recognizes as a place where CGI programs can
reside. Most web servers use a directory called cgi-bin for this by default,
but you, or your system administrator, can configure httpd to have any number
of CGI directories. We suggest creating a special directory for your DODS
servers to simplify maintaining them (but installing them in cgi-bin is
perfectly OK, too). [/var/www/cgi-bin]? "

read cgiDir
if test -z "$cgiDir"
then
    cgiDir="/var/www/cgi-bin"
fi

while test ! -d "${cgiDir}"
do
  echo $ac_n "${cgiDir} is not a directory, create it (y/n) [y]? "
  read yorn
  if test "${yorn}" = "y" -o "${yorn}" = "Y" -o -z "${yorn}"
  then
      mkdir ${cgiDir}
  else
      echo $ac_n \
"Where would you like the servers to be located on your system?"
      read cgiDir
  fi
done
echo  

if test ! -w $cgiDir
then
    echo "I cannot write to ${cgiDir}, you may need to re-run this script as
the super-user. Alternatively, try choosing a different directory."
    exit 1;
fi

if test "${server}" = "jg"
then

echo $ac_n \
"The DODS-JGOFS server installation will copy a default JGOFS method file
('def') and objects dictionary (.objects) onto your web server.  
These files ***should not*** be copied to a location that your httpd 
allows CGI programs to reside. The JGOFS 'def' method poses a security risk 
to a web site if stored in a CGI executible location.

We suggest creating a special directory for these local DODS-JGOFS
method files to insure the integrity of your web server, this can
be a subdirectory of your cgi-bin location. [${cgiDir}/jgofs]? "

read jgofsDir
if test -z "$jgofsDir"
then
    jgofsDir="${cgiDir}/jgofs"
fi

while test ! -d "${jgofsDir}"
do
  echo $ac_n "${jgofsDir} is not a directory, create it (y/n) [y]? "
  read yorn
  if test "${yorn}" = "y" -o "${yorn}" = "Y" -o -z "${yorn}"
  then
      mkdir ${jgofsDir}
  else
      echo $ac_n \
"Where would you like the servers to be located on your system?"
      read jgofsDir
  fi
done
echo  

if test ! -w $jgofsDir
then
    echo "I cannot write to ${jgofsDir}, you may need to re-run 
this script as the super-user. Alternatively, try choosing a different 
directory."
    exit 1;
fi

fi

#-----
# List files, show 
#-----
echo "The server(s) will be installed in $cgiDir"
echo

echo $ac_n \
"The DODS servers use a number of extra programs to get their job done. If
you are installing DODS for the first time, *or* are upgrading your servers
from an older version, chances are you will need to install these
programs and Perl modules.

"

# If the variables $addFiles and $addDirs change so should the lists of
# files/dirs in parentheses below. I wrote them out (instead of using the
# variable names) so that the text would appear nicely on the screen...
# 4/11/2001 jhrg.
echo $ac_n \
"Would you like the non-server-specific files (DODS_Cache.pm DODS_Dispatch.pm
FilterDirHTML.pm dods.rc nph-dods asciival deflate usage www_int and curl) 
and perl directory (HTML) to be installed? New copies won't hurt except in
very rare cases where servers customize versions of the programs.
(y/n) [y]? "

read yesNo
if test -z "$yesNo"
then
    yesNo="y"
fi

if test "${yesNo}" = "y" -o "${yesNo}" = "Y"
then
  yesNo="y"
else
  yesNo="n"
fi

#-----
# Copy files to cgi-bin
#-----
echo
echo $ac_n "Copying ${files}... "
cp ${files} ${cgiDir}
echo "done."
#-----
# Copy special JGOFS files..
#-----
if test "${server}" = "jg"
  then
    echo
    echo $ac_n "Copying ${jgfiles}... "

    cp ${jgfiles} ${jgofsDir}
    echo "done."

  fi

#-----
# Copy nph-dods (with change to use correct perl) to cgi-bin. Note that this
# does not try to substitute @PERL@ (or use the .in file) since configure may
# have a bunch of things to substitute in the .in file. This *just* fiddles
# with the Perl path at the front of the script. 4/11/2001 jhrg
#-----
sed "s@#!/.*perl@#!${PERL}@" < nph-dods > localized-nph-dods
mv localized-nph-dods $cgiDir/nph-dods

#-----
# If desired, copy additional files to cgi-bin
#-----
if test "${yesNo}" = "y"
then
    echo $ac_n "Copying ${addFiles}... "
    cp ${addFiles} ${cgiDir}
    echo "done."
    echo $ac_n "Copying ${addDirs}... "
    cp -r ${addDirs} ${cgiDir}
    echo "done."
fi
echo
echo

#-----
# set the execute mode bits of the nph-dods scripts
#-----
chmod 755 ${cgiDir}/nph-dods

#-----
# Do they want to register their site?
#-----
echo $ac_n \
"Would you like to register you site's DODS server(s)? If so I'll automatically
send an email message to the DODS/OPeNDAP project with this site's Internet
address. We won't share this address with anybody else, but it will help
us quantify the software's use.

"

while test -z "$register"; do
    echo $ac_n "Register this site (y/n) [n]? "
    read register;

    if test -z "$register"; then
	register="n"
    fi
    if test "$register" != "y" -a "$register" != "n"; then
	echo "I did not understand. Please answer 'y' or 'n.'"
	register=
    fi
done

echo

if test "$register" = "y"; then
    # does hostname contain the domain, too?
    if hostname | grep "\." > /dev/null 2>&1; then
	name=`hostname`
    else
        name="`hostname`.`domainname`"
    fi

    # NB: Use the machine name here and later when we set up the stats 
    # stuff 5/17/2002 jhrg
    until ping -c 1 "$machine" >/dev/null 2>&1; do
	if ping -c 1 "$name" >/dev/null 2>&1; then
	    echo $ac_n "Register your server/site name as [$name]: " 
	else
	    echo $ac_n "What host name should be registered (please give the full host name): "
	fi
	read machine
	if test -z "$machine"; then
	    machine=$name
	fi
    done 

    version=`./nph-dods 2>/dev/null | grep XDODS | sed 's@.*\(DAP/[0-9.]*\)@\1@'`
    mail -s "DODS Server Registration" $Server_Registration_Email <<EOF
Server: $machine
Version: $version
EOF
fi

echo

#-----
# Optionally set up the status stuff
#-----
if test $register = "y"; then
    echo $ac_n \
"Would you be willing to let us (DODS/OPeNDAP) gather access statistics from
your server? We understand that allowing access to the DODS/DAP server's
usage information might not be acceptable to you. However, allowing us access
to the server's usage information will help us direct future software
development efforts. If you choose to enable the server statistics feature,
only the local host and official DODS/OPeNDAP machines will be able to gain
access to the statistical information.

"

    stats=
    while test -z "$stats"; do
        echo $ac_n \
"Would you like us to gather statistics from your server (y/n)? [n] "

        read stats;
	if test -z "$stats"; then
	    stats="n"
	fi
	if test "$stats" != "y" -a "$stats" != "n"; then
	    stats=
	    echo $ac_n \
"I did not understand your response, please answer 'y' or 'n.'"
	fi
    done
    
    if test "$stats" = "y"; then
	# OK grab the names of the access and error logs.
	access_log=
	while test -z "$access_log"; do
	    echo $ac_n \
"What is the full pathname of your server's access log file 
[/var/log/httpd/access_log] ?"
	    read access_log
	    if test -z "$access_log"; then
		access_log=/var/log/httpd/access_log
	    fi
	    if ! test -f $access_log; then
		echo "The file $access_log does not exist."
		access_log=
	    fi
	    if ! test -r $access_log; then
		echo "The file $access_log cannot be read. Check its protections"
		access_log=
	    fi
	done

	error_log=
	while test -z "$error_log"; do
	    echo $ac_n \
"What is the full pathname of your server's error log file 
[/var/log/httpd/error_log] ?"
	    read error_log;
	    if test -z "$error_log"; then
		error_log=/var/log/httpd/error_log
	    fi
	    if ! test -f $error_log; then
		echo "The file $error_log does not exist."
		error_log=
	    fi
	    if ! test -r $error_log; then
		echo "The file $error_log cannot be read. Check its protections"
		error_log=
	    fi
	done

	machine_names="localhost|$machine"

	# Write the file "DODS_STATISTICS" with information about where to
	# gather stats information. Backup an existing DODS_STATISTICS file.
	# 09/27/02 jhrg 
	mv DODS_STATISTICS DODS_STATISTICS.bak 2>/dev/null
	
	echo "access_log $access_log" > DODS_STATISTICS
  	echo "error_log $error_log" >> DODS_STATISTICS
  	echo "machine_names $machine_names" >> DODS_STATISTICS

	echo -n "Coping DODS_STATISTICS to $cgiDir..."
	cp DODS_STATISTICS $cgiDir
	echo " done"
    fi
fi

echo

#-----
# Done, let user know.
#-----
echo "Install complete!

Please don't forget to read over INSTALL-servers."
