#!/bin/bash
###############################################################################
# Description:
# Get softiocs parameters like port, user, directory, command, needed to create 
# a configuration file for the shellbox service.
# Create/update /etc/shellbox.d/<port>.conf files
#
# $Id: shellbox_from_db,v 1.4 2014/05/22 08:06:45 kapeller Exp $
# $Source: /cvs/G/EPICS/App/scripts/shellbox_from_db,v $
###############################################################################
#

PATH="/usr/bin:/bin:/usr/sbin:/sbin"
SHELLBOX_DIR="/etc/shellbox.d"

# If user is not a real person, send notification to the following email addresses:
DEFAULT_EMAIL="rene.kapeller@psi.ch, renata.krempaska@psi.ch"

hostname=$(hostname -s)
progname=$(basename $0)
pid=$$
tmpfile="/tmp/$progname.tmp"
lockfile="/var/tmp/${progname}.lck"

###############################################################################
### functions

unlock() {
  rm -rf $lockfile
  exit 1
}

lock() {
  if [ -e $lockfile ]; then
    sub_perr "found $lockfile"
    exit 1
  else
    touch $lockfile
    trap unlock EXIT TERM INT
  fi
}

###############################################################################
### main

lock

if (wget -qO $tmpfile https://inventory.psi.ch/soap/softioc_info.aspx?host=$hostname); then
  mkdir -p $SHELLBOX_DIR
  rm $SHELLBOX_DIR/.[0-9]*.conf
  cat $tmpfile | tr -d '\r' | while IFS=$'\n' read line; do
    if [ -n "$line" ]; then
      port=$(echo $line | cut -d ' ' -f 1)
      user=$(echo $line | cut -d ' ' -f 2)
      email=$(ldapsearch -x -H ldap://d.psi.ch -b "ou=Users,ou=PSI,dc=d,dc=psi,dc=ch" "(cn=$user)" mail | grep @ | awk '{print $2}')
      if [ -z "$email" ]; then
        email=$DEFAULT_EMAIL
      fi
      new_file="$SHELLBOX_DIR/.${port}.conf"
      old_file="$SHELLBOX_DIR/${port}.conf"
      echo "#" > $new_file
      echo "# This file has been generated by $progname." >> $new_file
      echo "# Manual changes will get lost!" >> $new_file
      echo "#" >> $new_file
      echo "$line" >> $new_file
      echo "### EOF" >> $new_file
      if (! cmp -s $new_file $old_file); then
        subject="SoftIOC #$port on $hostname has changed"
        if [ -e $old_file ]; then
          diff -u $new_file $old_file | mail -s "$subject" $email
        fi
        cp $new_file $old_file
      fi
    fi
  done
fi
rm $tmpfile

# Delete what is not in the database
cd $SHELLBOX_DIR
for file in [0-9]*.conf; do
  if [ -e $file -a ! -e .$file ]; then
    subject="SoftIOC $file on $hostname has been deleted"
    mail -s "$subject" $DEFAULT_EMAIL < $file
    rm $file
  fi
done

unlock

### EOF
