#!/usr/bin/env bash
#
# Simple script to run octopus for all atoms in the 
# periodic table for which pseudopotentials are available.
#


# the defaults file
defaults=/usr/share/octopus/pseudopotentials/element.dat

# the octopus executable
octopus=/usr/bin/octopus

ECHO=""
fromScratch="yes"
no_states=0
smearing=0

# usage
function usage() {
    cat <<EOF

 Copyright (C) 2005 by Heiko Appel

Usage: oct-run_periodic_table [options]
    
     -h              this message
     -n              dry run mode (show what would be executed)
     -s species      run octopus for given species
     -a              run octopus for all atoms            
     -r              do a restart, i.e. do not use fromScratch=yes
     -t temperature  run with electronic temperature
     -e no_states    use extra states
     -x              octopus executable
     -d              element.dat file for pseudopotentials
     -p              choice of the pseudopotential set

Report bugs to <appel@physik.fu-berlin.de>.
EOF
 exit 0;
}


# show usage info if no args at all
[ "$#" -eq 0 ] && usage;

# process command line options
while getopts "hns:art:e:x:d:p:" opt ; do
    case "$opt" in
        h) usage ;;
        n) ECHO="echo" ;; 
        s) species="$OPTARG" ;;
        a) ECHO="" ;;
        r) fromScratch="no" ;;
        t) electronic_temp="$OPTARG" ;;
        e) no_states="$OPTARG" ;;
        x) octopus="$OPTARG" ;;
        d) defaults="$OPTARG" ;;
        p) pseudoset="$OPTARG" ;;
        ?) echo "Error parsing arguments"; exit 1 ;;
    esac
done
shift $(( OPTIND - 1 ))

# do we have all required files?
if [ ! -x $octopus  ]; then 
  echo "Error: could not find octopus executable: $octopus"
  exit 1
fi
if [ ! -f $defaults ]; then 
  echo "Error: could not find defaults file: $defaults"
  exit 1
fi

if [ "$species" = "" ]; then
  # for which atoms are pseudopotentials available?
  pseudos=$(awk '{ print $1 }' $defaults | grep -v "#")
else
  pseudos="$species"
fi

# loop over all pseudopotentials
for x in $pseudos; do

  # Extract atomic number
  atomic_no=$(grep -E "${x}[[:space:]]" $defaults | grep -v "#" | awk '{ print $2 }'); 

  # generate working directory
  workdir=$(printf "%02d_%s\n" ${atomic_no} ${x})
  $ECHO mkdir $workdir

  # setup input file
  if [ -d $workdir ]; then
    {
cat <<-EOF

CalculationMode = gs
FromScratch = $fromScratch

BoxShape = sphere

Radius = 7
Spacing = 0.5

PseudopotentialSet = $pseudoset
%Coordinates
  "$x" | 0 | 0 | 0
%

Eigensolver = chebyshev_filter
ExtraStates = $no_states

SmearingFunction = fermi_dirac
Smearing = $electronic_temp

EOF
    } >> $workdir/inp 2>/dev/null
    
  fi

  # change to working directory
  $ECHO pushd $workdir

  # run octopus
  echo "running $workdir ..."
  $ECHO nice -n 19 $octopus

  # change to previous directory
  $ECHO popd

done
