#!/bin/sh
set -u  # force better programming and ability to use check for not set
if [ "${1:-}" = "-x" ] ; then set -xv; shift; fi

# sbin/$RCSfile$  $Revision$

# script to cut the get and sdsscp products from the enstore cvs sources

# based on copCut which is based almost entirely on Ron R's dscCut

productCut=`basename $0`
echo "$productCut starting at `date`"
thepwd=`pwd`

##############################################################################
# utility functions that do what their names imply

# this function would be better if it actually did the command too, this
# would allow you to say "check_status command" rather than "command; check_status $? command.."
# Oh, well... next time
check_status() { jstatus=${1:-0}
                 jname=${2:-unknown}
                 jstep=${Step:-unknown}
                 if [ $jstatus != 0 ] ; then
                   echo ""
                   echo "$productCut Fatal Error=$1 \"$jname\", Step \"$jstep\"" >&2
                   echo "$productCut ABORTED at `date`"
                   cd $thepwd
                   exit $jstatus
                 else
                   if [ -z "${3-}" ] ; then
                      echo "$productCut success for \"$jname\", Step \"$jstep\" at `date`" >&2
                   fi
                 fi ; }

echo_timed_read() { jtime=${1:-10}
                    /bin/sh -c '( sleep '$jtime' ; kill $$ ) >/dev/null 2>&1 &
                    read ans ; echo "$ans"' ;}

starting() { if [ $try != "list" ] ; then
                /bin/echo -n "starting at `date`"
             fi; }

copyit()   { dname=`dirname $2`
             if [ ! -d $dname ]; then
               mkdir -p $dname
               check_status $? "mkdir -p $dname"
             fi
             if [ -f $1 ]; then
               cp $1 $2;
               check_status $? "cp $1 $2"
             fi ;}

plint() { echo $1
          python $GADFLY_GRAMMAR/kjpylint.py $1 | egrep -v "^setup$|^loading$|^now parsing$|ref at .* before assign at|defined before .* not used"
          echo
        }

##############################################################################

USAGE="

   $productCut -options

-r version   next release version
-i directory install directory (without version number and product) for the new revision (i.e. /p/Linux)
-c chain     to set chain to be <new|old|test|development|current|none>
-s steps     to control which steps get executed,  zB 1,2,4-13
-x           to set -xv
-?           to list this

Steps to the cutting process:
  1.  cvs directory check
  2.  lint check (continues if errors)
  3.  bump get version number in get.py
  4.  cd modules - make clean all
  5.  cd src - make clean get/sdsscp


  8.  compileall python source

 10.  install into product area
 11.  ups undeclare
 12.  ups declare
 13.  upd delproduct
 14.  upd addproduct
"

STEPSDEFINED=14

echo "$USAGE"

##############################################################################

product=`echo $productCut | sed -e 's/Cut//'`

if [ $product = "sdsscp" ]; then
  productmate=enstore
  productUps="/ups"
else
  check_status 1 "Do not know anything about $productCut"
fi

##############################################################################

# we need ups and upd to be setup

if [ -z "${UPS_DIR-}" ] ; then
  Step="ups check"
  check_status 1 "You need ups to be setup before using $productCut"
fi

if [ -z "${UPD_DIR-}" ] ; then
  Step="upd check"
  check_status 1 "You need upd to be setup before using $productCut"
fi

##############################################################################
# we need enstore to be setup and we need to be in a cvs working directory

if [ -z "${ENSTORE_DIR-}" ] ; then
  Step="enstore check"
  check_status 1 "You need enstore to be setup before using $productCut"
fi
cd $ENSTORE_DIR
check_status $? "cd $ENSTORE_DIR"
#FLAVOR=`echo $SETUP_ENSTORE | sed -e 's/.*-f //' -e 's/ .*//'`
#FLAVOR=`$UPS_DIR/bin/ups flavor -2`

# Take care of IRIX+6.5, Linux+2.2 and Linux+2.4

FLAVOR=`$UPS_DIR/bin/ups flavor -3`

case ${FLAVOR} in
        IRIX+6.5)
                ;;
	SunOS+5.7)
		;;
	SunOS+5.8)
		;;
	Linux+2.4)
		if [ `ups flavor -4` == "Linux+2.4-2.3.2" ]; then
			# Take care of Linux 9.0 and LTS.
			FLAVOR=`$UPS_DIR/bin/ups flavor -4`
		fi
		;;
	Linux+2.6*)
		;;
        *)
                FLAVOR=`$UPS_DIR/bin/ups flavor -2`
esac

if [ -d CVS ] ; then
   # who cares any way?
   # Cvs_Module=`expr "\`cat CVS/Repository\`" : ".*/\([^/]*\)"`
   Cvs_Module=`cat CVS/Repository`
fi
if [ "${Cvs_Module:-}" = "" ];then
   check_status 1 "You need to be in a cvs working directory to use $productCut"
fi

##############################################################################
# parse the options on the command line
#### dadburned getopts does not work on OSF1, so parse opts manually############

gotc=
QUALIFIERS=""
opt=""
if [ $# -gt 0 ] ; then
   for optarg in $@ ; do

      case $opt in
         -i) INSTALLDIR=$optarg
             opt=""
             ;;
         -r) REV=$optarg
             opt=""
             ;;
         -c) case $optarg in
               "")  CHAIN="";             ;;
               no*) CHAIN="";             ;;  # no or none
               c*)  CHAIN="${CHAIN-} -c"; ;;  # you can have multiple chains
               d*)  CHAIN="${CHAIN-} -d"; ;;
               n*)  CHAIN="${CHAIN-} -n"; ;;
               o*)  CHAIN="${CHAIN-} -o"; ;;
               t*)  CHAIN="${CHAIN-} -t"; ;;
                *)   Step="chain getopts"; check_status 1 "You have specified an illegal chain";  ;;
             esac
             gotc=1
             opt=""
             ;;
         -q) QUALIFIERS="-q $optarg"
             opt=""
             ;;
         -s) STEPS=`for i in \`echo $optarg | sed -e 's/,/ /g'\` ; do
                if x=\`expr $i : '\(.*\)-'\` ; then
                   y=\`expr $i : '.*-\(.*\)'\`
                   while [ $x -le $y -a $x -le $STEPSDEFINED ] ; do
                     echo $x
                     x=\`expr $x + 1\`
                   done
                else
                   echo $i
                fi
              done | sort -nu`        # do not sort if we want to specify an order or repeating steps (could use uniq instead of sort)
              STEPS="`echo $STEPS`"   # remove lfs (b/c STEPS isnt quoted inside)
              opt=""
              ;;
         "") opt=$optarg;;
         -?) echo "$USAGE"; Step="getopts"; check_status 1 "" ;;
         *)  echo "$USAGE"; Step="getopts"; check_status 1 "Unknown option" ;;
         esac
   done
fi

if [ -n "$opt" ] ; then echo "$USAGE"; Step="getopts"; check_status 1 "Can not parse command line correctly"; fi

echo ""
echo "options have been processed... checking"

##############################################################################
# we need a revision - if not specified, get old one from a cvs tag

if [ -z "${REV-}" ] ; then
   Step="next revision"
   last=`grep 'Revision:' $ENSTORE_DIR/src/get.py | tr -s ' ' ' ' | cut -f 4 -d' ' | cut -c2-`
   major=`echo $last | awk -F_ '{print $1}'`
   minor=`echo $last | awk -F_ '{print $2}'`
   REV=${major}_`expr $minor + 1`
   check_status $? "determining next rev from $last"
   echo "Revision not specified - Defaulting to revison $REV"
fi
TAG=${REV}_${product}_${FLAVOR}
TAG=`echo ${TAG} | tr "." "_"`

##############################################################################
# we need a place to install the cut product

setrev=1
puntUPS=0
if [ -z "${INSTALLDIR-}" ] ; then
   Step="installdir"
   case `uname -n` in
      airedale*) INSTALLDIR=/home/products/$product;;
      pcfarm9*)  INSTALLDIR=/products/$product;;
      hppc*)     INSTALLDIR=/usr/products/IRIX+6/$product;;
      ripsgi*)   INSTALLDIR=/usr/products/$product;;
      rip8*)     INSTALLDIR=/fnal/ups/prd/$product/${REV}/${FLAVOR}
                 setrev=0;;
      bld*)      INSTALLDIR=/afs/.fnal.gov/ups/sdsscp/${REV}/${FLAVOR}
                 setrev=0;;
      d0ola*)    INSTALLDIR=$ENSTORE_DIR/$product #this stinks! but I don't know what else to do
                 puntUPS=1;;
      *)         check_status 1 "Don't know where to install ups product $product on `uname -n`";;
   esac
   echo "Install directory not specified - Defaulting to install directory of $INSTALLDIR"
fi
if [ $setrev -eq 1 ]; then
  INSTALLDIR=${INSTALLDIR}/${REV}
fi

##############################################################################
# we need to know what steps we are supposed to perform during the cut

if [ -z "${STEPS-}" ] ; then
   STEPS=1
   s=2
   while [ $s -le $STEPSDEFINED ] ; do STEPS="${STEPS-} $s"; s=`expr $s + 1`; done
   echo "Cut steps not specified - Defaulting to all steps: $STEPS"
fi
STEPSOK=""
for step in $STEPS; do
   if [ $step -le $STEPSDEFINED -a $step -ge 1 ] ; then
      if [ -z "${STEPSOK-}" ] ; then
        STEPSOK=$step
      else
        STEPSOK="$STEPSOK $step"
      fi
   fi
done
if [ -z "${STEPSOK-}" ] ; then
  Step="checksteps"
  check_status 1 "No steps defined, how odd"
fi
STEPS=$STEPSOK
STEPS="$STEPS done" # done is flag that we are finished
save_STEPS=$STEPS

##############################################################################
# we need to know what chain we are cutting

if [ -z "${gotc-}" ] ; then
   CHAIN=" -c"
   echo "UPS/UPD chain not specified - Defaulting to chain $CHAIN"
fi

echo ""
echo "Using files in CVS $Cvs_Module working directory `pwd` to cut $product $REV"
echo "  and ups/upd declaring it as ($CHAIN) into directory $INSTALLDIR"
echo "  and using steps $save_STEPS."

##############################################################################

for try in list doit; do
   echo ""
   STEPS=$save_STEPS
   while [ "$STEPS" != "done" ] ; do
      Step="`expr \"$STEPS\" : '\([^ ]*\) .*'`"
      STEPS="`expr \"$STEPS\" : '[^ ]* \(.*\)'`"
      case $Step in

        1) echo "Step $Step:   cvs directory check for `pwd`    `starting`"
           if [ "$try" = "doit" ] ; then
              cd $ENSTORE_DIR
              check_status $? "cd $ENSTORE_DIR"
              cvs_nq_update=`cvs -nq update 2>&1`
              check_status $? "cvs -nq update: $cvs_nq_update"
              if echo "$cvs_nq_update" | fgrep '[server aborted]' >/dev/null ; then
                check_status 1 "server aborted problems with cvs: $cvs_nq_update"
              elif x="`echo \"$cvs_nq_update\"|grep '^M'`"   ; then
               check_status 1 "$x: Modified or unknown files ($cvs_nq_update) in working directory - update/commit needed first"
              elif x="`echo \"$cvs_nq_update\"|grep '^[PU]'`"; then
               check_status 1 "$x: Update/Patched files ($cvs_nq_update) in repository - update/commit needed first"
              fi
           fi
           ;;

        2) echo "Step $Step:   lint the python source   `starting`"
           if [ "$try" = "doit" ] ; then
              pyfiles=/tmp/$productCut.pyfiles
              find $ENSTORE_DIR/src -name "*.py" >$pyfiles
              cat $pyfiles | while read pfile; do
                 $ENSTORE_DIR/tools/mylint.py $pfile
                 check_status $? "$ENSTORE_DIR/tools/mylint.py $pfile"
		 $ENSTORE_DIR/tools/check_pct.py -w $pfile
                 check_status $? "$ENSTORE_DIR/tools/check_pct.py -w $pfile"
              done
              rm $pyfiles
           fi
           ;;

        3) echo "Step $Step:   bump get version number to $REV in get.py   `starting`"
           if [ "$try" = "doit" ] ; then
              cd $ENSTORE_DIR/src
              check_status $? "cd $ENSTORE_DIR/src"
              cvs update -A get.py
              check_status $? "cvs update -A get.py"
              getnew=/tmp/$productCut.getnew
              sed -e "s+version_string = \".*  CVS +version_string = \"$REV  CVS +" $ENSTORE_DIR/src/get.py > $getnew
              check_status $? "sed bump version to $REV"
              diff $ENSTORE_DIR/src/get.py $getnew
              cp $getnew $ENSTORE_DIR/src/get.py
              check_status $? "mv $getnew $ENSTORE_DIR/src/get.py"
              rm -f $getnew
              cvs commit -m "bumping version to $REV because of $productCut" get.py
              check_status $? "cvs commit of get.py"
              cvs tag -F production get.py
              check_status $? "cvs tag -F production get.py"
           fi
           ;;

        4) echo "Step $Step:   cd modules and make clean all   `starting`"
           if [ "$try" = "doit" ] ; then
              cd $ENSTORE_DIR/modules
              check_status $? "cd $ENSTORE_DIR/modules"
              make clean all
              check_status $? "make clean all"
           fi
           ;;

        5) echo "Step $Step:   cd src and make clean get/sdsscp    `starting`"
           if [ "$try" = "doit" ] ; then
              cd $ENSTORE_DIR/src
              check_status $? "cd $ENSTORE_DIR/src"
              make clean get
              check_status $? "make clean get"

	      cd $ENSTORE_DIR/ingest/sdss
              check_status $? "cd $ENSTORE_DIR/ingest/sdss"
              make clean sdsscp
              check_status $? "make clean sdsscp"
           fi
           ;;

	6) echo "Step $Step:"
	    ;;
        #6) echo "Step $Step:   cd volume_import and make clean enstore_tape    `starting`"
        #   if [ "$try" = "doit" ] ; then
        #      cd $ENSTORE_DIR/volume_import
        #      check_status $? "cd $ENSTORE_DIR/volume_import"
        #      make clean enstore_tape
        #      check_status $? "make clean enstore_tape"
        #   fi
        #   ;;

	7) echo "Step $Step:"
	    ;;
        #7) echo "Step $Step:   cd doc/WWW - make all    `starting`"
        #   if [ "$try" = "doit" ] ; then
        #      if [ $product = "enstore" ]; then
        #      cd $ENSTORE_DIR/doc
        #      check_status $? "cd $ENSTORE_DIR/volume_import"
        #      make clean all
        #      check_status $? "docs make clean all"
        #      else
        #         echo "No make needed for documentation of sdsscp"
        #      fi
        #   fi
        #   ;;

        8) echo "Step $Step:   compileall python source   `starting`"
           if [ "$try" = "doit" ] ; then
             find $ENSTORE_DIR -name "*\.pyc" | xargs rm
             check_status $? "rm of old pyc files"
             compileall_output=/tmp/$productCut.compileall_output
             python -c '
import os,compileall
compileall.compile_dir(os.environ["ENSTORE_DIR"])
' 2>&1 | tee $compileall_output
             check_status $? "compileall python source"
             if [ `grep -c "SyntaxError" $compileall_output` -ne 0 ]; then
               check_status 1 "compile error - see $compileall_output"
             else
               rm -f $compileall_output
             fi
           fi
           ;;

	9) echo "Step $Step:"
	    ;;
        #9) echo "Step $Step:   cvs tag -F $TAG    `starting`"
        #   if [ "$try" = "doit" ] ; then
        #      cd $ENSTORE_DIR
        #      check_status $? "cd $ENSTORE_DIR"
        #      cvs tag -F $TAG
        #      check_status $? "cvs tag -F $TAG"
        #   fi
        #   ;;

       10) echo "Step $Step:  install $product into $INSTALLDIR    `starting`"
	  if [ "$try" = "doit" ] ; then
	     # check if directory doesn't exist
	     if [ ! -d $INSTALLDIR ] ; then
		echo "$INSTALLDIR does not exist... making it"
		mkdir -p $INSTALLDIR
		check_status $? "mkdir -p $INSTALLDIR"
             else
                 rm -fr $INSTALLDIR
                 check_status $? "protections bad??  rm -fr $INSTALLDIR"
             fi

	     if [ $product = "sdsscp" ]; then 
	     
	         copyit $ENSTORE_DIR/src/SDSSCP_BIN/get           $INSTALLDIR/get
		 copyit $ENSTORE_DIR/src/SDSSCP_BIN/sdsscp        $INSTALLDIR/sdsscp
		 copyit $ENSTORE_DIR/src/SDSSCP_BIN/chooseConfig  $INSTALLDIR/chooseConfig
		 copyit $ENSTORE_DIR/src/SDSSCP_BIN/sdsscp.table  $INSTALLDIR/sdsscp.table
		 copyit $ENSTORE_DIR/src/SDSSCP_BIN/enroute2      $INSTALLDIR/enroute2
		 # So far, make setuid installation manual
                 #chmod u+s $INSTALLDIR/enroute2

		 manifest=$INSTALLDIR/.sdsscpCut.manifest
 	     fi

             filelist=/tmp/$productCut.filelist
             find $INSTALLDIR -type f > $filelist
             check_status $? "find $INSTALLDIR -type f > $filelist"
             cat $filelist | while read f; do
               s=`sum $f`
               check_status $? "s=`sum $f`" quiet
               echo $f $s >>$manifest
               check_status $? "echo $f $s >>$manifest" quiet
             done
             rm -f $filelist
             set | grep _DIR= | egrep -v "export|EMACS|ISPELL"| sort >>$manifest

             find $INSTALLDIR -type d | xargs chmod 555
             check_status $? "find $INSTALLDIR -type d | xargs chmod 555"
             find $INSTALLDIR -type f | xargs chmod -w
             check_status $? "find . -type f | xargs chmod -w"
             chmod 555 $INSTALLDIR
             check_status $? "chmod 555 $INSTALLDIR"

             if [ $puntUPS -eq 1 ]; then
                rm -f $HOME/${product}_$REV.tar
                cd $INSTALLDIR/..
                check_status $? "cd $INSTALLDIR"
                basen=`basename $INSTALLDIR`
                tar -cf $HOME/${product}_$REV.tar $basen
                check_status $? "tar -cf $HOME/${product}_$REV.tar $INSTALLDIR"
             fi
           fi
           ;;

       11) echo "Step $Step:  ups undeclare -f $FLAVOR $product $REV    `starting`"
           if [ "$try" = "doit" ] ; then
              if [ $puntUPS -ne 1 ]; then
                a=`$UPS_DIR/bin/ups undeclare $QUALIFIERS -f $FLAVOR $product $REV 2>&1`
                stat=$?
                if [ `echo "$a" | grep -c "No matching product"` -eq 0 ]; then
                  check_status $stat $a
                fi
              else
                echo "PUNTING: ups undeclare  $QUALIFIERS -f $FLAVOR $product $REV"
              fi
           fi
           ;;

       12) echo "Step $Step:  ups declare $CHAIN $QUALIFIERS -f $FLAVOR -r $INSTALLDIR -M ${INSTALLDIR}${productUps} -m $product.table $product $REV    `starting`"
           if [ "$try" = "doit" ] ; then
              if [ $puntUPS -ne 1 ]; then
                 $UPS_DIR/bin/ups declare $CHAIN $QUALIFIERS -f $FLAVOR -r $INSTALLDIR -M ${INSTALLDIR}${productUps} -m $product.table $product $REV
                 check_status $? "ups declare"
              else
                 echo "PUNTING: ups declare $CHAIN $QUALIFIERS -f $FLAVOR -r \`pwd\` -M \`pwd\`${productUps} -m $product.table $product $REV"
              fi
           fi
           ;;

       13) echo "Step $Step:  upd delproduct $QUALIFIERS -H $FLAVOR -f $FLAVOR  $product $REV   `starting`"
           if [ "$try" = "doit" ] ; then
              if [ $puntUPS -ne 1 ]; then
                a=`$UPD_DIR/bin/upd delproduct $QUALIFIERS -H $FLAVOR -f $FLAVOR $product $REV 2>&1`
                stat=$?
                if [ `echo "$a" | grep -c "No matching product"` -eq 0 ]; then
                  check_status $stat $a
                fi
              else
                echo "PUNTING: upd delproduct $QUALIFIERS -H $FLAVOR -f $FLAVOR $product $REV"
              fi
           fi
           ;;

       14) echo "Step $Step:  upd addproduct $CHAIN $QUALIFIERS -H $FLAVOR -f $FLAVOR -r $INSTALLDIR -M ${INSTALLDIR}${productUps} -m $product.table $product $REV   `starting`"
           if [ "$try" = "doit" ] ; then
              if [ $puntUPS -ne 1 ]; then
                $UPD_DIR/bin/upd addproduct $CHAIN $QUALIFIERS -H $FLAVOR -f $FLAVOR -r $INSTALLDIR -M ${INSTALLDIR}${productUps} -m $product.table $product $REV
                check_status $? "upd addproduct"
              else
                echo "PUNTING: upd addproduct $CHAIN $QUALIFIERS -H $FLAVOR -f $FLAVOR -r \`pwd\` -M \`pwd\`${productUps} -m $product.table $product $REV"
              fi
           fi
           ;;


        *) check_status 1 "There is no step \"$Step\". Why did you ask for it?"
           ;;

       esac
   done

   if [ "$try" = "list" ] ; then
      /bin/echo -n "\nThere are a total of $STEPSDEFINED steps defined. Is this the set that you want to do? "
      ans=`echo_timed_read 10`
      if [ $? != 0 ] || expr "$ans" : '[Yy]' >/dev/null ; then
        echo "Proceeding with $productCut..."
        echo ""
    else
         cd $thepwd
         check_status $? "cd $thepwd"
         exit 0
      fi
  fi
done

cd $thepwd
echo "$productCut $REV finished at `date`"
