#!/bin/sh

if [ -z "$ARC_LOCATION" ] ; then
  if [ ! -z "$NORDUGRID_LOCATION" ] ; then
    ARC_LOCATION="$NORDUGRID_LOCATION"
  fi
fi

if [ -z "$ARC_CONFIG" ] ; then
  if [ ! -z "$NORDUGRID_CONFIG" ] ; then
    ARC_CONFIG="$NORDUGRID_CONFIG"
  fi
fi

revfile=`ls -1 /etc/*-revision 2>/dev/null | head -n 1`
if [ ! -z "$revfile" ] ; then
  revname=`basename $revfile '-revision'`
else
  revfile=`ls -1 /etc/*-version 2>/dev/null | head -n 1`
  if [ ! -z "$revfile" ] ; then
    revname=`basename $revfile '-version'`
  fi
fi
if [ ! -z "$revfile" ] ; then
  revision=`cat "$revfile" | head -n 1`
  if [ ! -z "$revision" ] ; then
    echo "frontend_distribution=\"$revname $revision\""
  fi
fi
sysinfo=`uname -a 2>/dev/null | head -n 1`
if [ ! -z "$sysinfo" ] ; then
  echo "frontend_system=\"$sysinfo\""
fi
hostcert=$X509_USER_CERT
if [ -z "$hostcert" ] ; then hostcert=$X509_HOST_CERT ; fi
if [ -z "$hostcert" ] ; then hostcert='/etc/grid-security/hostcert.pem' ; fi
if [ -r "$hostcert" ] ; then
  hostsubject=`openssl x509 -in /etc/grid-security/hostcert.pem  -subject -noout 2>/dev/null | head -n 1 | sed 's/^subject= *//'`  
  hostissuer=`openssl x509 -in /etc/grid-security/hostcert.pem  -issuer -noout 2>/dev/null | head -n 1 | sed 's/^issuer= *//'`  
  if [ ! -z "$hostsubject" ] ; then
    echo "frontend_subject=\"$hostsubject\""
  fi
  if [ ! -z "$hostissuer" ] ; then
    echo "frontend_ca=\"$hostissuer\""
  fi
fi
if [ ! -z "$ARC_LOCATION" ] ; then
  ngversion=` "$ARC_LOCATION/sbin/grid-manager" -v 2>/dev/null | head -n 1 | sed 's/^.*version *//'`
  if [ ! -z "$ngversion" ] ; then
    echo "frontend_middleware=\"nordugrid-arc-$ngversion\""
  fi
fi

if [ ! -z "$ARC_CONFIG" ] ; then
  lrms=`grep '^lrms=' "$ARC_CONFIG" 2>/dev/null | head -n 1 | sed 's/^lrms=//;s/"//g'`
  if [ ! -z "$lrms" ] ; then
    echo "frontend_lrms=\"$lrms\""
  fi
fi

if [ -r /proc/cpuinfo ] ; then
  processor=
  cat /proc/cpuinfo | \
  sed 's/^vendor_id//;s/^model name//;s/^cpu MHz//;t exit;s/.*//;:exit' | \
  sed 's/^[[:blank:]]*.[[:blank:]]*//' | {
    while true; do 
      read line
      if [ $? -ne 0 ]; then
        if [ ! -z "$processor" ] ; then
          echo "frontend_processor=\"$processor\""
        fi
        break
      fi
      if [ -z "$line" ] ; then continue; fi
      processor="$processor $line"
    done
  }
fi

if [ -r /proc/meminfo ] ; then
  memory=`cat /proc/meminfo | \
  sed 's/^MemTotal:[[:blank:]]*//;t exit;s/.*//;:exit'`
  if [ ! -z "$memory" ] ; then
    echo "frontend_memory=\"$memory\""
  fi
fi

