#!/bin/ksh
usage()
{
  echo "hmcusers: -o [ add | delete ] -h <list of hmc hosts>"
  echo "          -l <login> -u <list of user names> -a <hmc access>"
  echo "   -o     The operation to perform, add or delete users."
  echo "   -h     The list of HMC perform the operation."
  echo "   -l     The login to use on HMC to perform the operation."
  echo "   -u     The list of user to create."
  echo "   -a     The access on HMC."
  exit 1
}

while getopts "o:h:l:u:a:" _arg; do
   case $_arg in
   o) op=$OPTARG
	 ;;
   h) hl=$OPTARG
	;;
   l) lid=$OPTARG
	;;
   u) ul=$OPTARG
	;;
   a) access=$OPTARG
	;;
   *) usage
      ;;
   esac
done
if [ "$op" == "" ]; then
   echo "operation not specified"
   usage
fi
if [ "$hl" == "" ]; then
   echo "host list not specified"
   usage
fi
if [ "$lid" == "" ]; then
   echo "login id not specified"
   usage
fi
if [ "$ul" == "" ]; then
   echo "user names not specified"
   usage
fi

if [ "$op" == "add" ]; then
  # some validation here
  if [ "$access" == "" ]; then
     echo "missing HMC access role."
     usage
  fi
  for i in $hl
  do
    ping -c 1 $i >/dev/null 2>&1
    if [ $? -ne 0 ]; then
          echo "Unable to contact "$i
          echo "Skipping this host."
          continue
    fi
    for u in $ul
    do
       pass=$u$RANDOM
       ssh $lid@$i mkhmcusr -u $u -a $access -d "User $u" --passwd $pass -M 90
       if [ $? -eq 0 ]; then
	  echo "Created user "$u" with default password "$pass" on "$i
       else
	  echo "Failed to create user "$u" on "$i
       fi	
    done 
  done
fi
if [ "$op" == "delete" ]; then
  for i in $hl
  do
    ping -c 1 $i >/dev/null 2>&1
    if [ $? -ne 0 ]; then
          echo "Unable to contact "$i
          echo "Skipping this host."
          continue
    fi
    for u in $ul
    do
       ssh $lid@$i rmhmcusr -u $u
       echo "in delete"
       if [ $? -eq 0 ]; then
	  echo "Deleted user "$u" on "$i
       else
	  echo "Failed to delete user "$u" on "$i
       fi	
    done
  done
fi
