# New Yaim Configuration and setup for D-Cache 1.6.6-X
# Maintained by Owen Synge on behalf of GridPP
# Based upon work by 
# M Litmaath, M de Riese, J Mencak, J Novak,L Poncent, O Keeble, L Field and M Aart
# which based thier work upon d-cache configuration adapted 
# from package d-cache-lcg

# GridPP's testing has been very useful

# This script is based upon earlier work by LHC

# Structure of this script

# Yaim utility functions come first in this script, these are placed 
# here to avoid dependacy issues as these are functions that will be 
# Needed by many components, D-Cache in particular makes use of 
# these utilities



# functions starting yaim_query_conf

# This script was always designed as a way to make modification easy
# To this end set up questions are placed at the top of the file. This
# is intended to make porting Yaim to debconf or any other cluster wide 
# management system easy. These functions are queries that could in 
# practice be queries to an interactive installer or a cluster 
# management system

#
# functions starting yaim_state

# These functions are to establish the state of the install and direct 
# what components are to be installed. They do not change the state 
# of uninstalled/installed components


# functions starting yaim_config






## Start of yaim query functions


yaim_query_conf_node_dcache_pnfsserver()
{
    # Returns 0 when node is not a pnfsserver node
    # Returns 1 when node is a pnfsserver node
    local result
    local NameSpaceMan
    yaimlog DEBUG "function yaim_query_conf_node_dcache_pnfsserver start"
    result=0
    yaim_query_conf_node_dcache_name_server
    isANameServer=$?
    if [ 1 == "${isANameServer}" ] ; then
        if [ -n "${DCACHE_PNFS_SERVER}" ] ; then
            result=1
        fi
        
    fi
    yaimlog DEBUG "function yaim_query_conf_node_dcache_pnfsserver stop"
    return ${result}
}



# Returns List of pnfs servers. 
# This should only ever be one host, but is a "list" to be consistent
yaim_query_conf_node_dcache_pnfsserver_list()
{
    # Returns 0 when node is not a pnfsserver node
    # Returns 1 when node is a pnfsserver node
    local result
    local thishost
    RET=""
    if [ -z "${DCACHE_PNFS_SERVER}${DCACHE_CHIMERA_SERVER}${DCACHE_NAME_SERVER}" ] ; then
        RET=""
    else
	if [ -n "${DCACHE_PNFS_SERVER}" ] ; then
            RET="${DCACHE_PNFS_SERVER}"
        fi        
	if [ -n "${DCACHE_NAME_SERVER}" ] ; then
            RET=""
        fi
        if [ -n "${DCACHE_CHIMERA_SERVER}" ] ; then
            RET=""
        fi
    fi
    return 0
}







yaim_query_conf_node_dcache_pnfs_root()
{
  yaimlog DEBUG "function yaim_query_conf_node_dcache_pnfs_root start"
  if [ -d /opt/pnfs.3.1.10/pnfs/ ] ; then
    RET=/opt/pnfs.3.1.10/pnfs/
  fi
  if [ -d /opt/pnfs/ ] ; then
    RET=/opt/pnfs/
  fi
  yaimlog DEBUG "function yaim_query_conf_node_dcache_pnfs_root stop"
}

## End of yaim query functions
## Start of yaim state functions

yaim_state_reset_pnfs() {
  # Returns 0 when postgres is fine
  # Returns 1 when postgres should be removed
  yaimlog DEBUG "function yaim_state_reset_pnfs start"
  result=0
  if [ "X$RESET_DCACHE_PNFS" == Xyes ] ; then
    result=1
  fi
  yaimlog DEBUG "function yaim_state_reset_pnfs stop"
  return $result
}


## End of yaim state functions
## Start of yaim config functions


config_pnfs_uninstall()
{
  yaimlog DEBUG "function config_pnfs_uninstall start"
  yaim_query_conf_node_dcache_pnfs_root
  PNFSROOT=$RET
  PNFS_CONFIG="${PNFSROOT}/etc/pnfs_config"
  if [ -f "${PNFS_CONFIG}" ] ; then
  
    PNFS_DB=`cat $PNFS_CONFIG 2> /dev/null| grep PNFS_DB | awk '{print $3}'` 
    if [ "X$PNFS_DB" != "X" ] ; then
      if [ -d $PNFS_DB ]; then
        rm -rf $PNFS_DB
      fi
    fi
  else
    echo WARNING SKIPPING removal of PNFS
  fi
  yaimlog DEBUG "function config_pnfs_uninstall stop"
}


config_pnfs_install_script()
{
  yaimlog DEBUG "function config_pnfs_install_script start"
  yaim_query_conf_node_dcache_pnfs_root
  PNFSROOT=$RET
  if [ -n "${PNFSROOT}" ] ; then
    pushd ${PNFSROOT} > /dev/null 2>&1
      if [ -x  install/pnfs-install.sh ] ;  then
        install/pnfs-install.sh
	pnfsinstallsuc=$?
	if [ 0 == pnfsinstallsuc ] ; then
	  yaimlog ERROR "calling ${PNFSROOT}/install/pnfs-install.sh"
	  yaimlog ERROR "failed aborting"
	  exit 1
	fi
      else
        yaimlog ERROR "could not find pnfs-install.sh"
        yaimlog ERROR "Please install PNFS using apt-get"
        yaimlog ERROR "Please use the following command to establish"
        yaimlog ERROR "available versions."
        yaimlog ERROR "apt-cache search pnfs"
        exit 1
      fi
    popd > /dev/null 2>&1
  fi
  yaimlog DEBUG "function config_pnfs_install_script stop"
}



config_pnfs_install()
{
  yaimlog DEBUG "function config_pnfs_install start"
  yaim_query_conf_node_dcache_pnfs_root
  PNFSROOT=$RET  
  if [ ! -f ${PNFSROOT}/etc/pnfs_config ] ; then
    if [ -f "${PNFSROOT}/etc/pnfs_config.template" ] ; then 
      configFile=${PNFSROOT}/etc/pnfs_config
      yaim_config_file_update_prepare ${configFile}
      file2update=$RET
      cp ${PNFSROOT}/etc/pnfs_config.template $file2update
      if [ $? != 0 ] ; then
        yaimlog ABORT "cp ${PNFSROOT}/etc/pnfs_config.template ${PNFSROOT}/etc/pnfs_config"
        exit 1
      fi
      # Finished editng values
      yaim_config_file_update_done ${configFile}
      if [ $? != 0 ] ; then 
          yaim_state_service_restart_needed pnfs
          yaimlog WARNING "Changed the file ${configFile}"
      fi
    fi
  fi
  # As installing pnfs wipes /usr/etc/pnfsSetup
  # Yaim should back it up
  if [ -f /usr/etc/pnfsSetup ] ; then
    yaim_config_file_backup "/usr/etc/pnfsSetup"
    rm /usr/etc/pnfsSetup
  fi
  config_pnfs_install_script
  yaimlog DEBUG "function config_pnfs_install stop"
}





config_pnfs_start() {
  yaimlog DEBUG "function config_pnfs_start start"
  if [ -f /etc/init.d/pnfs ] ; then
    yaim_query_conf_node_dcache_pnfsserver
    tmptrue=$?
    if [ "x${tmptrue}" == "x1" ] ;then
      /etc/init.d/pnfs stop
      /etc/init.d/pnfs start
    fi
  else
    yaimlog WARNING "file /etc/init.d/pnfs does not exist"
  fi
  
  yaimlog DEBUG "function config_pnfs_start stop"
}

config_pnfs_stop() {
  yaimlog DEBUG "function config_pnfs_stop start"
  if [ -f /etc/init.d/pnfs ] ; then  
    yaim_query_conf_node_dcache_pnfsserver
    tmptrue=$?
    if [ "x${tmptrue}" == "x1" ] ;then
      /etc/init.d/pnfs stop
    fi
  else
    yaimlog WARNING "file /etc/init.d/pnfs does not exist"
  fi    
  yaimlog DEBUG "function config_pnfs_stop stop"
}





# Returns the pnfs database id by name
config_dcache_pnfs_database_get_id()
{
  yaimlog DEBUG "function config_dcache_pnfs_database_get_id start"
  local_vo=$1
  if [ "X${local_vo}" == "X" ] ; then
    yaimlog ABORT config_dcache_pnfs_database_get_id does not include the VO parameter
    exit 1
  fi
  yaim_query_conf_node_dcache_pnfs_root
  pnfs=${RET}
  RET=$($pnfs/tools/mdb show |  sed -e "1,2d" | sed -e 's/  */ /g' | grep $local_vo | cut -f2 -d" ")
  yaimlog DEBUG "function config_dcache_pnfs_database_get_id stop"
}

# Returns the number of pnfs databases
config_dcache_pnfs_database_count_get()
{
  yaimlog DEBUG "function config_dcache_pnfs_database_count_get start"
  current_vo=$1
  yaim_query_conf_node_dcache_pnfs_root
  pnfs=${RET}
  RET=$($pnfs/tools/mdb show | tail -n 1 | cut -b -4)
  yaimlog DEBUG "function config_dcache_pnfs_database_count_get stop"
}

# Returns the number of slots available for
# the pnfs databases
config_dcache_pnfs_database_shmservers_get()
{
  yaim_config_file_get_value /usr/etc/pnfsSetup shmservers 0
  RET=$RET
}


# Sets the number of slots available for
# the pnfs databases to 16 more than used 
# if less than 5 free slots are available
config_dcache_pnfs_database_shmservers_set()
{
  yaimlog DEBUG "function config_dcache_pnfs_database_shmservers_set start"
  config_dcache_pnfs_database_count_get
  clients=$RET
  padded_clients=$(expr $clients + 1)
  config_dcache_pnfs_database_shmservers_get
  servers=000${RET}
  count_padded_clients=$(expr "$padded_clients" : '[0-9]*')
  count_servers=$(expr "$servers" : '[0-9]*')
  while [ ${count_padded_clients} \< $count_servers ]
  do
    padded_clients=0${padded_clients}
    count_padded_clients=$(expr "$padded_clients" : '[0-9]*')
  done
  yaimlog DEBUG "clients=$padded_clients servers=$servers"
  if [ "$padded_clients" -ge "$servers" ] ; then
    yaimlog INFO "No free pnfs db server slots adding 16"
    new_server_count=$(expr ${clients} + 16)
    
    yaim_config_file_update_prepare "/usr/etc/pnfsSetup"
    updateFile=$RET
    yaim_config_file_set_value "${updateFile}" "shmservers" "$new_server_count"
    yaim_config_file_update_done "/usr/etc/pnfsSetup"
    if [ $? != 0 ] ; then 
	yaimlog WARNING "Changed the file '/usr/etc/pnfsSetup'"
	config_pnfs_stop
        config_pnfs_start
    fi
  fi
  yaimlog DEBUG "function config_dcache_pnfs_database_shmservers_set stop"
}





# Gets the wormhole ID which is needed by many
# D-cache command line tools when changing the 
# pnfs file system
config_dcache_pnfs_database_wormholePnfsId_get()
{
  RET=$(cat '/pnfs/fs/admin/etc/.(id)(config)')
}





# Gets the shared mem ID which is needed by many
# D-cache command line tools when changing the 
# pnfs file system
config_dcache_pnfs_database_shmkey_get()
{
  yaim_config_file_get_value /usr/etc/pnfsSetup shmkey 0
  RET=$RET  
}


# Gets the directory where VO's can write
config_dcache_pnfs_vo_dir_get()
{
  if [ -z "$DCACHE_PNFS_VO_DIR" ] ; then
    RET="/pnfs/${MY_DOMAIN}/data"
  else
    RET=${DCACHE_PNFS_VO_DIR}
  fi
}

# Gets the directory where pnfs databases 
# used to be stored
config_dcache_pnfs_database_dir_get()
{
  RET=/opt/pnfsdb/pnfs/databases/
}



# Create a new pnfs data base with the name
# as the first parameter if the database
# is exists this just returns the ID
config_dcache_pnfs_database_id_get_create()
{
  this_vo="$1"
  if [ "X${this_vo}"  == "X" ] ;then
    yaimlog ABORT "No VO provided"
    exit 1
  fi
  # Get the ID of reasently created VO
  config_dcache_pnfs_database_get_id ${this_vo}
  pnfs_id=$RET
  if [ "X${pnfs_id}" == "X" ] ; then
    config_dcache_pnfs_database_dir_get
    pnfsdb_base_dir=$RET
    yaim_query_conf_node_dcache_pnfs_root
    pnfs=${RET}
    ${pnfs}/tools/mdb create "${this_vo}" "${pnfsdb_base_dir}/${this_vo}"
    touch "${pnfsdb_base_dir}/${this_vo}"
    ${pnfs}/tools/mdb update
    config_dcache_pnfs_database_get_id ${this_vo}
    pnfs_db_key=$RET
  fi
}

# Creates the VO directory and the subdirectory "generated"
config_dcache_pnfs_vo_dir_create()
{
  yaimlog DEBUG "function config_dcache_pnfs_vo_dir_create start"
  local vo_pool_account
  currentVo="$1"
  if [ "X${currentVo}"  == "X" ] ;then
    yaimlog ABORT "No VO provided"
    exit 1
  fi
  # Make sure we have enough pnfs comunication 
  # slots to makethings work
  config_dcache_pnfs_database_shmservers_set
  config_dcache_pnfs_database_id_get_create "$currentVo"
  pnfs_id=$RET
  config_dcache_pnfs_vo_dir_get
  thisvodir=$RET
  mkdir -p "${thisvodir}/.($pnfs_id)($currentVo)"
  # check the directory exists as with PNFS the 
  # return code of mkdir cant be trusted.
  dirExists=$(file ${thisvodir}/${currentVo} | cut -d: -f2)
  if [ "${dirExists}" != " directory" ] ; then
    # directory not created yet 
    sleep 1
    dirExists=$(file ${thisvodir}/${currentVo} | cut -d: -f2)
    if [ "${dirExists}" != " directory" ] ; then
      yaimlog WARN "PNFS is responding slowly YAIM is waitign for pnfs to create ${thisvodir}/${currentVo}"
      sleep 10
      dirExists=$(file ${thisvodir}/${currentVo} | cut -d: -f2)
      if [ "${dirExists}" != " directory" ] ; then
        yaimlog ERROR "PNFS is did not create ${thisvodir}/${currentVo} fast enough YAIM is exiting."
        exit 1
      fi    
    fi
  fi
  config_dcache_pnfs_database_shmkey_get
  PnfsShMemId=$RET
  config_dcache_pnfs_database_wormholePnfsId_get
  PnfsWormHoleId=$RET
  yaim_query_conf_node_dcache_pnfs_root
  pnfs=${RET}
  ${pnfs}/tools/sclient getroot ${PnfsShMemId} ${pnfs_id} ${PnfsWormHoleId} > /dev/null
  echo "StoreName ${currentVo}" > "${thisvodir}/${currentVo}/.(tag)(OSMTemplate)"
  echo "STATIC" > "${thisvodir}/${currentVo}/.(tag)(sGroup)"
  #Now make a subdriectory
  currentVoGenerated=${currentVo}.generated
  config_dcache_pnfs_database_shmservers_set
  config_dcache_pnfs_database_id_get_create "$currentVoGenerated"
  pnfs_id=$RET
  mkdir -p "${thisvodir}/${currentVo}/.($pnfs_id)(generated)"
  config_dcache_pnfs_database_shmkey_get
  PnfsShMemId=$RET
  config_dcache_pnfs_database_wormholePnfsId_get
  PnfsWormHoleId=$RET
  yaim_query_conf_node_dcache_pnfs_root
  pnfs=${RET}
  ${pnfs}/tools/sclient getroot ${PnfsShMemId} ${pnfs_id} ${PnfsWormHoleId} >/dev/null
  echo "StoreName ${currentVo}" > "${thisvodir}/${currentVo}/generated/.(tag)(OSMTemplate)"
  echo "GENERATED" > "${thisvodir}/${currentVo}/generated/.(tag)(sGroup)"
  # Give VO write access 
  
  users_VoGetsGid ${currentVo}
  users_VoGetsGidrc=$?
  VoGID=${RET}
  if [ "${users_VoGetsGidrc}" != 0 ] ; then
    yaimlog ERROR "users_VoGetsGid returned an error exiting"
    exit 4
  fi
  if [ -n "${VoGID}" ] ; then
    chown -R :${VoGID} "${thisvodir}/${currentVo}"
  fi
  chmod -R 775 "${thisvodir}/${currentVo}"
  yaimlog DEBUG "function config_dcache_pnfs_vo_dir_create stop"
}


# Iterates through the VO's and tries to create the 
config_dcache_pnfs_databases()
{
  yaimlog DEBUG "function config_dcache_pnfs_databases start"
  local rcpnfsserver
  yaim_query_conf_node_dcache_pnfsserver
  rcpnfsserver=$?
  if [ "${rcpnfsserver}" == 1 ] ; then
    for thisvo in ${VOS}
    do
      config_dcache_pnfs_vo_dir_get
      vo_dir=$RET/$thisvo
      if [ ! -d "${vo_dir}" ] ; then
        config_dcache_pnfs_database_get_id $thisvo
        apnfsdbid=$RET
        if [ -n "$apnfsdbid" ] ; then
          yaimlog WARNING "No action needed '$thisvo' has its own pnfs DB already"
        else
          yaimlog INFO "$vo_dir does not exist creating"
          config_dcache_pnfs_vo_dir_create "$thisvo"
        fi
      fi  
    done
  fi
  yaimlog DEBUG "function config_dcache_pnfs_databases stop"
}

config_sepnfs_installed()
{
  yaimlog DEBUG "function config_sepnfs_installed start"
  yaim_query_conf_node_dcache_pnfs_root
  PNFSROOT=$RET
  PNFS_INSTALL=${PNFSROOT}/install/pnfs-install.sh
  if [ ! -x "${PNFS_INSTALL}" ] ; then
    yaimlog ERROR could not find pnfs-install.sh
    yaimlog ERROR Please install PNFS using apt-get
    yaimlog ERROR Please use the following command to establish
    yaimlog ERROR available versions.
    yaimlog ERROR apt-cache search pnfs
    exit 1
  fi
  
  yaimlog DEBUG "function config_sepnfs_installed stop"
}




config_sedcache_cron_create_chown() 
{
yaimlog DEBUG "function config_sedcache_cron_create_chown start"
local file_config_sedcache_cron_create
local pnfsbasedir
local VOGIDS
file_config_sedcache_cron_create=$1

config_dcache_pnfs_vo_dir_get
pnfsbasedir=$RET


for VO in $VOS
do
  users_VoGetsGid $VO
  VOGIDS="${VOGIDS} ${VO}:$(echo $RET | cut -d, -f1)"
done


sed -e "s/%%%/\$/g" -e "s/###/\`/g" <<EOF>${file_config_sedcache_cron_create}
#! /bin/sh
# Maintained by Owen Synge on behalf of dCache
# Based upon work by Patrick Fuhrmann
# Created while installing dCache
pnfs="${pnfsbasedir}"
vos="${VOGIDS}" 

d=%%%(/bin/date -d tomorrow +%Y-%m-%d)
for vogid in %%%vos; do
  vo=###echo "%%%{vogid}" | cut -d: -f1 ###
  gid=###echo "%%%{vogid}" | cut -d: -f2 ###
  mkdir -p     "%%%pnfs/%%%vo/generated/%%%d"
  chown :%%%{gid}  "%%%pnfs/%%%vo/generated/%%%d"
  chmod 0775   "%%%pnfs/%%%vo/generated/%%%d"
done

#
# delete old empty dirs in generated
#
for vogid in %%%vos; do
  vo=###echo "%%%{vogid}" | cut -d: -f1 ###
  gid=###echo "%%%{vogid}" | cut -d: -f2 ###
  find %%%pnfs/%%%vo/generated/200* -type d -empty -ctime +2 -exec rmdir {} \;
done
EOF
yaimlog DEBUG "function config_sedcache_cron_create_chown stop"
}




config_sepnfs_cron()
{
local pnfs_permsions
pnfs_permsions=${INSTALL_ROOT}/d-cache/libexec/pnfsperms.sh

# Now if we are the pnfs node we must set up some directories to protect
# Our selves from the big bad grid.
yaim_query_conf_node_dcache_pnfsserver
rcNameServer=$?
if [ "$rcNameServer" == 1 ]
then
  
  
  yaim_config_file_update_prepare ${pnfs_permsions}
  file2update=$RET
  config_sedcache_cron_create_chown ${file2update}
  yaim_config_file_update_done ${pnfs_permsions}
  if [ $? != 0 ] ; then 
    yaimlog WARNING "Changed the file ${pnfs_permsions}"
  fi  
  
  
  
  chmod 0755 ${pnfs_permsions}
  job="12 22 * * * root ${pnfs_permsions}"
  cron_job pnfs-permsions root "$job"
  ${pnfs_permsions}
fi

}


config_pnfs_install_mount()
{
  yaimlog DEBUG "function config_pnfs_install_mount start"
  local rcfoundpnfs
  local newfstabline
  local pnfsserverhostname
  local pnfsserverdomname
  local file2update
  local mountdev
  local mountdir
  yaim_query_conf_node_dcache_pnfsserver_list
  pnfsserverhostname=$RET
  pnfsserverdomname=$(echo ${pnfsserverhostname} | cut -d. -f2-)
  mountdev=${pnfsserverhostname}:/pnfsdoors
  mountdir=/pnfs/${pnfsserverdomname}
  yaim_config_file_update_prepare /etc/fstab
  file2update=$RET
  grep "${mountdev}" ${file2update} > /dev/null
  if [ 0 != $? ] ; then
    newfstabline="${mountdev} ${mountdir}  nfs hard,intr,ro,bg,noac,auto 0 0"
    echo ${newfstabline} >> ${file2update}  
  fi
  yaim_config_file_update_done /etc/fstab
  if [ $? != 0 ] ; then 
    yaimlog WARNING "Changed the file /etc/fstab"
  fi
  if [ ! -d "${mountdir}" ] ; then
    mkdir -p ${mountdir}
  fi
  mount  | grep "${mountdev}" >/dev/null
  if [ 0 != $? ] ; then
    yaimlog INFO "Please wait mounting ${mountdir}"
    mount ${mountdir}
    yaimlog INFO "Finished mounting ${mountdir}"
  fi
  yaimlog DEBUG "function config_pnfs_install_mount stop"
}

config_sedcache_pnfs() 
{
  # Check to see if postgres should be reinstalled
  yaimlog DEBUG "function config_sedcache_pnfs start"
  local rcrmdcconf
  local rcgsiftpdoornode
  # Check to see if PNFS should be installed
  yaim_query_conf_node_dcache_pnfsserver
  rcrmdcconf=$?
  if [ "$rcrmdcconf" == 1 ]
  then
    yaim_state_reset_pnfs
    rcrmdcconf=$?
    if [ "$rcrmdcconf" == 1 ]
    then
      config_pnfs_stop
      config_pnfs_uninstall
      config_pnfs_install
      yaimlog INFO "Done Resetting D-Caches PNFS"
    else
      yaimlog INFO "Skipping PNFS Reset"
    fi
    config_pnfs_start
    # Restart pnfs as the first time around PNFS server fails dont know why!
    config_pnfs_stop
    config_pnfs_start
  else
    yaim_query_conf_node_gsiftp_door
    rcgsiftpdoornode=$?
    if [ "$rcgsiftpdoornode" == 1 ]
    then
      config_pnfs_install_mount
    fi
  
  fi
  yaimlog DEBUG "function config_sedcache_pnfs stop"
}
config_sepnfs_check()
{
  return 0
}

config_sepnfs_run()
{
   config_sedcache_pnfs
}

config_sepnfs()
{
  local rcpnfsserver
  if [ "yes" == "$DESYOVERRIDE" ] ; then
    return 0
  fi
}
