#!/bin/bash -f
#-*- sh -*-
# getPwd gets and prints the password of the given resource.
#
# Auth: Greg White, 10-Jun-2010.
#
# Mod: K Brobeck, 27-Oct-2010
#
function usage {
echo "
  getPwd gets and prints the password of the given resource.

  Usage: 
          getPwd [-h] resourcename

  Examples: getPwd aida
            getPwd machine_model

  Options:
  
  -h (optional) Prints this help.
    
  When used on production, getPwd requires that the account from 
  which it is being used, is either physics, or an account that is DSA 
  authenticated to the physics account. Such accounst include softegr and
  eoicdesk. When used from AFS (say a tersk machine) then the user must 
  additionally be authenticated to their own account on lclc-prod02. These 
  are the normal conditions for users of the LCLS control system, 
  so if you are having trouble with getPwd, consult the LCLS Systems team.

  The mechanism is described in SimpleProdPasswordServer_v1_4_1, in 
  sharepoint at http://tinyurl.com/2u6qao6. It was reviewed by relevant SLAC
  and control system authorities.
"
}

while getopts h opt
do
   case "$opt" in
       h) usage; exit 0 ;;
       *) echo "Unknown option, see getPwd -h"; exit 1;;
   esac
done
shift $((OPTIND-1))
if [ $# -lt 1 ]; then
   echo "Too few arguments, see getPwd -h"
   exit 1;
fi

#
#Only the lclsdev network needs to login to prod02 first
#-so if you can ping lcls-srv01 then ssh directly to srv01
# -Added "-x" to speed things up
#
OS=`uname -a | awk '{print $1}'`
if [ "$OS" = Linux ]
  then
    PINGABLE=`ping -c1 -w1 lcls-srv01 >/dev/null; echo $?`
  else
    PINGABLE=`ping -c1 lcls-srv01 1 >/dev/null; echo $?`
fi

if [ "$PINGABLE" = 0 ]; then
    ssh -qxlmcckey lcls-srv01 /home/mcckey/.ssh/.private/gimmePwd ${1}  2>/dev/null
else 
    ssh -qx mcclogin.slac.stanford.edu ssh -qxlmcckey lcls-srv01 '/home/mcckey/.ssh/.private/gimmePwd' ${1}
fi

exit $?
