#!/bin/bash
# vim: ai ts=2 sw=2 et sts=2 ft=sh

PWD="/home/easybuild/git/it4i-modules"
cd $PWD || exit 1

STATE=$(git fetch 2>&1 | grep master)
if [ ! -z "$STATE" ]; then
  git pull
  ./get_modules.sh
  exit 0
fi

CLUSTER="$CLUSTERNAME"
if [ -z "$CLUSTER" ]; then
   echo "CLUSTERNAME not defined"
   exit 1
fi

if [ "$CLUSTER" == "ANSELM" ]; then
  ml --show-hidden -t av 2>&1 | awk '{print $1 ",1"}' | grep -v -e '/,\|:' | sort -u > anselm.csv
  ./modules.py > anselm.md
elif [ "$CLUSTER" == "SALOMON" ]; then
  ml --show-hidden -t av 2>&1 | awk '{print $1 ",2"}' | grep -v -e '/,\|:' | sort -u > salomon.csv
  ./modules.py > salomon.md

  for resource in "/appsuv/modules,uv2000" "/apps/phi/modules,phi"
  do
    MODULEBASE=${resource%,*}
    MODULEPATH=""
    FILENAME=${resource#*,}

    for dir in "$MODULEBASE"/*
    do
      # Exclude following directories
      if [ "$(basename "$dir")" == "all" ]; then
        continue
      fi
      # In case that it's directory
      if [ -d "$dir" ]; then
        if [ -z $MODULEPATH ]; then
          MODULEPATH=$dir
        else
          MODULEPATH="$MODULEPATH:$dir"
        fi
      fi
    done

    export MODULEPATH

    if [ "$MODULEBASE" == "/appsuv/modules" ]; then
       ml --show-hidden -t av 2>&1 | awk '{print $1 ",4"}' | grep -v -e '/,\|:' | sort -u > "$FILENAME".csv
       ./modules.py > "$FILENAME".md
    else
       ml --show-hidden -t av 2>&1 | awk '{print $1 ",8"}' | grep -v -e '/,\|:' | sort -u > "$FILENAME".csv
       ./modules.py > "$FILENAME".md
    fi

  done
elif [ "$CLUSTER" == "DGX" ]; then
   ml --show-hidden -t av 2>&1 | awk '{print $1 ",16"}' | grep -v -e '/,\|:' | sort -u > dgx.csv
  ./modules.py > dgx.md
elif [ "$CLUSTER" == "BARBORA" ]; then
   ml --show-hidden -t av 2>&1 | awk '{print $1 ",32"}' | grep -v -e '/,\|:' | sort -u > barbora.csv
     ./modules.py > barbora.md
elif [ "$CLUSTER" == "KAROLINA" ]; then
   ml --show-hidden -t av 2>&1 | awk '{print $1 ",64"}' | grep -v -e '/,\|:' | sort -u > karolina.csv
        ./modules.py > karolina.md
fi

DATE=$(date -R)
git diff --exit-code || git commit -am "$DATE"
git push origin master
