#!/bin/bash

if [ -d /projects/nlpl ]; then
  host="abel";
  root="/projects/nlpl";
elif [ -d /proj/nlpl ]; then
  host="taito";
  root="/proj/nlpl";
elif [ -d /projappl/nlpl ]; then
  host="puhti";
  root="/projappl/nlpl";
fi

if [ -z "${host}" ]; then
  echo "unable to locate NLPL project directory; exit."
  exit 1;
fi

start=$(date "+%y-%m-%d-%H:%M");
log="${root}/operation/log/${host}/users.${start}";

{
  if [ "${host}" = "abel" ]; then

    #
    # first things first: make sure we are running current scripts
    #
    cd ${root}/operation/users;
    svn up;

    #
    # locate the file providing Abel user information
    #
    if [ -f /cluster/var/user-info ]; then
      file="/cluster/var/user-info";
    else
      file="/tmp/.discovery.oe.$$";
      scp -o StrictHostKeyChecking=no -o CheckHostIP=no \
        login0.abel.uio.no:/cluster/var/user-info ${file};
    fi  

    #
    # retrieve the up-to-date list of active users, record, and pass it on
    #
    ./abel ${file} > ./abel.txt;
    svn diff ./abel.txt
    svn commit -m "automated discovery on ${host}" ./abel.txt
    if [ $(hostname) = "sh.hpc.uio.no" ]; then
      {
        /usr/lib/mailman/bin/list_members team;
        cat abel.txt csc/users.txt;
      } | sort -u \
      | /usr/lib/mailman/bin/sync_members -w -g -a -f - users;
    fi
  elif [ "${host}" = "puhti" ]; then

    #
    # first things first: make sure we are running current scripts
    #
    cd ${root}/operation/users;
    svn up;

    #
    # see whether martin matthiesen has left notes from the user database
    # 
    svn diff ./csc
    svn commit -m "automated discovery on ${host}" ./csc
  fi    

} > ${log} 2>&1

if [ $(cat ${log} | wc -l) -gt 2 -o $(date "+%u") -eq 1 ]; then
  cat ${log} | mailx -r oe@ifi.uio.no -s "cron(8): user discovery on ${host}" infrastructure@nlpl.eu;
fi
