#! /bin/sh

#    Dec 03/08 - F.Majaess (Revised for sa/saiph, ib/dorval-ib, af/alef)
#    Oct 16/06 - F.Majaess (Revised for ma/maia, ns/naos)
#    Mar 01/06 - F.Majaess (Revised for rg/rigel)
#    Jun 20/03 - F.Majaess (Revised for az/azur)
#    Feb 25/02 - F.Majaess (Revised for ya/yata)
#    Sep 14/00 - F.Majaess (Revised for tu/tsunami)
#    Jan 05/00 - F.Majaess (Added kz/kaze)
#    Jan 21/99 - F.Majaess (Added yo/yonaka)
#    Jul 14/97 - F.Majaess (Added sx/hiru)
#    Mar 18/97 - F.Majaess (Revise for group restructuring)
#    Mar 18/96 - F.Majaess (revise for SX-4)
#    Jun 21/95 - F.Majaess (Added orion, gandalf & aragorn)
#    Nov 08/94 - F.Majaess (Modify for sx3r and new destination identifiers)
#    May 28/93 - E. Chan (Increase default time limit to 200 sec)
#    Dec 14/92 - E. Chan (Modify to add change in ownership and add new 
#                         positional parameters "account" and "runpath")
#    Dec 03/92 - E. Chan   
 
#id  chgown  - submits a job to move the specified file from the user's 
#id            own run directory to another user's run directory and 
#id            change the ownership.
 
#    AUTHOR - E. Chan  
 
#hd  PURPOSE - "chgown" submits a job to the destination machine and moves
#hd            the specified file from the user's own run directory to 
#hd            another user's run directory (possibly on another machine if
#hd            the destination is one of the back-end machines). 
#hd            The corresponding link on the official CCRD/N data directory 
#hd            ('$DATAPATH') is modified accordingly.
#hd 
#hd            By default, the file with the highest edition number will be
#hd            affected. The "ed" parameter may be used to specify a 
#hd            particular edition number.
#hd  
#hd            Note: The job must be submitted to the machine where the
#hd                  file "pfn" is currently residing.
 
#pr  PARAMETERS:
#pr  
#pr    POSITIONAL
#pr 
#pr      account = account of new owner of the file   
#pr 
#pr          pfn = name of saved file 
#pr  
#pr      runpath = run directory of new owner
#pr   
#pr    PRIMARY
#pr   
#pr      Note: One of 'ha/sp/po/ca/mz'  in Dorval.
#pr
#pr          ha = to target job to IBM (hadar).
#pr
#pr          sp = to target job to IBM (spica).
#pr
#pr          po = to target job to Linux (pollux).
#pr
#pr          ca = to target job to Linux (castor).
#pr
#pr          mz = to target job to Linux (mez).
#pr
#pr
#pr  fil_grpname= User has the option of specifying one of
#pr               'ccrn_shr/ccrn_stf/ccrn_net/ccrn_rcm/ccrn_mam/ccrn_gst'
#pr               group ownership for targeted, officially saved 
#pr               file.
#pr               (=$DEFFGRP).
#pr
#pr          ed = edition number of saved file (default: the latest edition)
#pr 
#pr        time = time limit for job in seconds (=200)
#pr  
#pr         mem = memory limit for job in megabytes (=25)
#pr  
#pr 
 
#ex  EXAMPLE: 
#ex  
#ex  chgown acrnxxx dmm17sp /sx/crbs0/data fil_grpname='ccrn_shr' ha
#ex 
#ex  The above example moves the latest edition on Hadar of "dmm17sp" 
#ex  from the user's run directory to the user acrnxxx's run directory 
#ex  (/sx/crbs0/data). The file ownership and corresponding link on the official 
#ex  data directory is changed accordingly.
#ex  
#ex  chgown acrnxxx dmm17sp /sx/crbs0/data po 
#ex 
#ex  The above example moves the latest edition of "dmm17sp" from the user's run
#ex  directory on Pollux into acrnxxx's run directory (/sx/crbs0/data) and 
#ex  setup the corresponding link if necessary on the official data directory. 
#ex  Then the file is deleted from SX(s) along with the corresponding link.

#  * Obtain any specified option. 

for arg in $@
do
  case $arg in
        -x) set $arg                                       ;;
       *=*) eval $arg                                      ;;
      ed=*) ed=`expr $arg : 'ed=\([0-9]*\)'`               ;;
        ha) mdest=${mdest:='hadar'}                        ;;
        sp) mdest=${mdest:='spica'}                        ;;
        po) mdest=${mdest:='pollux'}                       ;;
        ca) mdest=${mdest:='castor'}                       ;;
        mz) mdest=${mdest:='mez'}                       ;;
         *) tmp2=${pfn:+$arg} ; runpath=${runpath:=$tmp2}  ;
            tmp1=${account:+$arg} ; pfn=${pfn:=$tmp1}      ;
            account=${account:=$arg}
  esac
done

#  * Prompt for positional parameters if missing.
 
while [ -z "$account" ] 
do
  echo "Enter the account to which the file is be transferred: > \\c"
  read account
done

while [ -z "$pfn" ] 
do
  echo "Enter the name of the file to be transferred: > \\c"
  read pfn
done

while [ -z "$runpath" ] 
do
  echo "Enter the run directory of the new owner: > \\c"
  read runpath
done

#  * Prompt for a destination if none was specified.

while [ -z "$mdest" ]
do
 if [ "$SITE_ID" = 'Victoria' ] ; then
   mdest="$HOSTID"
 elif [ "$SITE_ID" = 'Dorval' ] ; then
  echo "please enter a destination; ha/sp/po/ca/mz: > \\c"
  read tmdest
  case $tmdest in
      ha) mdest='hadar'                 ;;
      sp) mdest='spica'                 ;;
      po) mdest='pollux'                ;;
      ca) mdest='castor'                ;;
      mz) mdest='mez'                   ;;
       *) echo "illegal destination ! " ;;
  esac
 elif [ "$SITE_ID" = 'Downsview' ] ; then
   mdest="$HOSTID"
 else
  echo "please enter a destination: > \\c"
  read mdest
 fi
done

#  * Set the defaults.

time=${time:=200}
mem=${mem:=25}
nonqs=${nonqs:=$NONQS}
nonqs=${nonqs:='no'}

#  * If edition number is specified remove leading zeros in the edition 
#  * number and ensure that three digits are used. 

if [ -n "$ed" ] ; then
  ed=`expr $ed + 0`
  if [ "$ed" -lt 100 ] ; then
    ed=0$ed
  fi
  if [ "$ed" -lt 10 ] ; then
    ed=0$ed
  fi
fi
# fil_grpname=${fil_grpname:='ccrn_shr'}
if [ "$SITE_ID" = 'Dorval' ] ; then
 DEFFGRP=${DEFFGRP:='ccrn_shr'}
 fil_grpname=${fil_grpname:=$DEFFGRP}
fi
if [ -n "$fil_grpname" ] ; then
 Tfil_grpname="fil_grpname=$fil_grpname && export fil_grpname "
else
 Tfil_grpname=" : "
fi

#   * Check parameter values.

chkrl=" chgown account=$account pfn=$pfn runpath=$runpath ed=$ed  "
chkrl=" $chkrl fil_grpname=$fil_grpname mdest=$mdest"
. checker | more -e

#  * Construct and submit the job.

if [ "$mdest" = 'hadarl' ] ; then
  outdest=$OUTPUTQ/chgown_${pfn}.ha.$$
elif [ "$mdest" = 'spica' ] ; then
  outdest=$OUTPUTQ/chgown_${pfn}.sp.$$
elif [ "$mdest" = 'pollux' ] ; then
  outdest=$OUTPUTQ/chgown_${pfn}.po.$$
elif [ "$mdest" = 'castor' ] ; then
  outdest=$OUTPUTQ/chgown_${pfn}.ca.$$
elif [ "$mdest" = 'mez' ] ; then
  outdest=$OUTPUTQ/chgown_${pfn}.mz.$$
else
  outdest=$OUTPUTQ/chgown_${pfn}.$$
fi

same='yes'
# disabled #>if [ "$mdest" = 'cidsc03' -o "$mdest" = 'sx3r' -o "$mdest" = 'asa' ] ; then
# disabled #>#!! sbemchn=`echo "$runpath" | sed -n -e 's/^\/data\/c3r.*$/sx3r/p' `
# disabled #>#!! sdatapath=${sbemchn:+'/data/c3rsrc/data'}
# disabled #> sbemchn=`echo "$runpath" | sed -n -e 's/^\/data\/3r.*$/sx3r/p' `
# disabled #> sbemchn=${sbemchn:=`echo "$runpath" | sed -n -e 's/^\/data\/asa_.*$/asa/p' `}
# disabled #> sbemchn=${sbemchn:-'cidsc03'}
# disabled #> case $sbemchn in
# disabled #>   asa) sdatapath='/data/asa_ccrd/src/data' ;;
# disabled #>  sx3r) sdatapath='/data/3rsrc/data'    ;;
# disabled #>    * ) sdatapath="${BEDATAPATH}" ;;
# disabled #> esac
# disabled #># sdatapath=${sbemchn:+'/data/3rsrc/data'}
# disabled #># if [ -n "$sbemchn" -a "$sbemchn" = 'asa' ] ; then
# disabled #>#  sdatapath=${sdatapath:='/data/asa_ccrd/data'}
# disabled #># fi
# disabled #># sdatapath=${sdatapath:-'/data/c3src/data'}
# disabled #># sdatapath=${sdatapath:-${BEDATAPATH}}
# disabled #> if [ "$mdest" != "$sbemchn" ] ; then
# disabled #>  same='no'
# disabled #> fi
# disabled #>fi

# qsub -q $mdest -lT $time -lM ${mem}mb -r chgown.$pfn \
# qsub -q $mdest -lT $time -lM ${mem}mb -r chgown \
#                -eo -o $outdest <<endjob
if [ "$nonqs" = 'yes' ] ; then
 if [ "$mdest" = "$HOSTID" ] ; then
  line="nohup sh -s - 1>>$outdest 2>>$outdest & "
 else
  echo "CHGOWN: Sorry, nohup is limited to the same platform"
  echo "        mdest=$mdest; HOSTID=$HOSTID !"
  exit 1
 fi
else
 line="qsub -q $mdest -lT $time -lM ${mem}mb -r chgown -eo -o $outdest"
fi
#
cd $HOME/tmp
(cat <<endjob) | eval "$line"
#!/bin/sh
#
AWK=\${AWK:='awk'}
$Tfil_grpname
if [ "$same" = "yes" ] ; then
  cd $runpath 
fi
#
#  * Obtain the absolute path to the desired file.
#
if [ -n "$ed" ] ; then
  line=\`ls -l \$DATAPATH/$pfn.$ed 2>/dev/null\`
else
  line=\`ls -l \$DATAPATH/$pfn.[0-9][0-9][0-9] 2>/dev/null | tail -1\` 
fi
if [ -z "\$line" ] ; then
  echo "Error in chgown: file $pfn does not exist" 
  exit 1 
fi
#
file=\`expr "\$line" : '.* \{1,\}\([^ ]*\)$'\`
ownacct=\`whoami\`
line2=\`echo \$line | fgrep \$ownacct\`
if [ -z "\$line2" ] ; then
  echo "Error in chgown: file \$file is not owned by \$ownacct" 
  echo "                 --- ownership is not changed ---"
  exit 2
fi
#
#  * If the file is to remain on the same machine:
#  * Change the ownership of the file, move the file to the new owner's
#  * run directory, and adjust the link on the official data directory to 
#  * reflect the change. If the run directory is the same as the data directory,
#  * then there is no need for a link. 
#
if [ "$same" = "yes" ] ; then
 mv \$file $runpath
 if [ "\$?" -eq 0 ] ; then
  name=\`expr //\$file : '.*/\(.*\)'\`
  if [ -n "\$fil_grpname" ] ; then
   chgrp \$fil_grpname \$name
  fi
  chown $account \$name
  touch \$name
  if [ \$DATAPATH/\$name != $runpath/\$name ] ; then
    rm -f \$DATAPATH/\$name
    ln -s $runpath/\$name \$DATAPATH/\$name
  fi
  echo "\$file has been moved to $runpath/\$name"
 fi
else
#
#  * If the file is to be moved to another back-end machine:
#  * Copy the file into the new machine; verify the transfer is complete,
#  * change ownership, possibly setup the link on the remote machine
#  * data directory and finally remove the file from local machine (with
#  * the link).
#
 sline=\`rsh $sbemchn ls $sdatapath/$pfn.[0-9][0-9][0-9] | tail -1 | grep $pfn \`
 if [ -z "\$sline" ] ; then
  ed='1'
 else
  ed=\` expr \$sline : '.*\\.\\([0-9][0-9][0-9]\\)\$'\`
  ed=\` expr \$ed + 1 \`
 fi
 if [ "\$ed" -lt 100 ] ; then
  ed=0\$ed
  if [ "\$ed" -lt 10 ] ; then
   ed=0\$ed
  fi
 fi
 if [ "\$ed" -gt 999 ] ; then
  echo "Abort in chown: trying to save edition \$ed on $sbemchn (max: 999)"
  exit 1
 fi
 sline2=\`rsh $sbemchn ls $sdatapath/$pfn.\$ed | tail -1 | grep $pfn \`
 if [ -n "\$sline2" ] ; then
  echo "Abort in chown: file $sdatapath/$pfn.\$ed already exists on $sbemchn"
  exit 2
 fi
 if [ $sdatapath != $runpath ] ; then
  sline2=\`rsh $sbemchn ls $runpath/$pfn.\$ed | tail -1 | grep $pfn \`
  if [ -n "\$sline2" ] ; then
   echo "Abort in chown: file $runpath/$pfn.\$ed already exists on $sbemchn"
   exit 3
  fi
 fi
 Xpctsz=\`ls -al \$file | \$AWK '{ print \$5 ; } '\`
 rcp -p \$file $sbemchn:$runpath/$pfn.\$ed
 Actlsz=\`rsh $sbemchn ls -al $runpath/$pfn.\$ed | \$AWK '{ print \$5 ; } '\`
 if [ "$Xpctsz" != "$Actlsz" ] ; then
  echo "Abort in chown: Incomplete dataset transfer to $sbemchn:$runpath/$pfn.\$ed"
  exit 4
 fi
 rsh $sbemchn 'chgrp \$fil_grpname $runpath/$pfn.\$ed'
 rsh $sbemchn 'chown $account $runpath/$pfn.\$ed'
 if [ $sdatapath != $runpath ] ; then
  rsh $sbemchn 'ln -s $runpath/$pfn.\$ed $sdatapath/$pfn.\$ed'
 fi
 rm -f \$file 
 name=\`expr //\$file : '.*/\(.*\)'\`
 if [ \$DATAPATH/\$name != \$file ] ; then
  rm -f \$DATAPATH/\$name
 fi
 echo "$mdest:\$file has been moved to $sbemchn:$runpath/$pfn.\$ed"
fi
#
( rmllfls || : )
exit

endjob

exit
