#!/bin/bash

set -e

Help()
{
    ## Display Help
    echo "schemas [-h|-e|-r] Update derived schema files, needs IMPNA env"
    echo "options:"
    echo "h     Print this help."
    echo "e     STAFID  add stafid"
    echo "r     REPCODE add add repcode"
    echo
}

if [ -z $IMPNA ]; then
    >&2 echo "I need an IMPNA environment"
    exit
fi

# Get the options
while getopts ":h:r:e:" option; do
    case $option in
        h) # display Help
            Help
            exit;;
        e) # Enter a stafid
           add_stafid=$OPTARG;;
        r) # Enter a repcode
           add_repcode=$OPTARG;;
    esac
done

run_trang=/usr/bin/trang
# echo $IMPNA
if [ -z $IMPNA ] && [ -z $1 ]; then
    echo "I need an impna"
    exit
fi
if [ -z $IMPNA ]; then
    cand_impna=$1
    if [ ! -d $HOME/ernad/style/$cand_impna ]; then
        echo "I do not see your impna $cand_impna"
        exit
    fi
    IMPNA=$cand_impna
fi

if [ ! -e $run_trang ]; then
    echo "I can not run $run_trang"
    exit
fi

# echo "~/ernad/bin/filids $IMPNA -r $add_repcode -e $add_stafid"
## run filids first to get the file-based identifiers
if [ -z $add_repcode ] && [ -z $add_stafid ]; then
    ~/ernad/bin/filids
elif [ -z $add_repcode ]; then
    ~/ernad/bin/filids $IMPNA -e $add_stafid
elif [ -z $add_stafid ]; then
    ~/ernad/bin/filids $IMPNA -r $add_repcode
else
    ~/ernad/bin/filids $IMPNA -r $add_repcode -e $add_stafid
fi

in_dir=$HOME/ernad/schema/$IMPNA
## needs to be in sink with erimp determination
# ou_dir=$HOME/ernad/opt/schema/$IMPNA
## no erimp-specific
ou_dir=$HOME/ernad/opt/schema


## an a testing installation, we use a different an
## impna-specific file for the issuedates
if [ -f /etc/wpa_supplicant.conf ]; then
    issuedates_fufi=~/ernad/opt/schema/issuedates.rng.xml
    impna_dates_fufi=~/ernad/opt/schema/${IMPNA}_issuedates.rng.xml
    if [ ! -f ~/ernad/opt/schema/issuedates.rng.xml ]; then
        /usr/bin/cp $impna_dates_fufi $issuedates_fufi
    fi
fi

#rng_fufi=$HOME/ernad/schema/$IMPNA/staff_$IMPNA.rng.xml
# staff_dir=$in_dir
for in_fufi in "$in_dir/"*.rng.xml; do
    # /usr/bin/xmllint --relaxng $rng_fufi $fufi > /dev/null 2> $lint_fufi
    # echo $fufi
    # # let's skip dated files
    if [[ $in_fufi =~ [0-9]{4}-[0-9]{2}-[0-9]{2}.rng.xml ]]; then
        continue
    fi
    if [ ! -f $in_fufi ]; then
        continue
    fi
    if [ ! -z $do_verbose ]; then
        echo "I read $in_fufi"
    fi
    bana="${in_fufi##*/}"
    ## remove .rng.xml
    bana="${bana:0:-8}"
    ou_fufi=$ou_dir/$bana.rnc
    $run_trang -I rng -O rnc $in_fufi $ou_fufi
    error=$?
    if [ $error -eq 0 ]; then
        if [ ! -z $do_verbose ]; then
            echo "I wrote $ou_fufi"
        fi
        continue
    fi
done

## change files from .rng.rnc to simple .rnc
for ou_fufi in "$ou_dir/"*.rng.rnc; do
    /usr/bin/mv $ou_fufi "${ou_fufi:0:-8}".rnc
done
#

## fix references to .rng.rnc files
/usr/bin/perl -pi -e 's|\.rng\.rnc"|.rnc"|' ~/ernad/opt/schema/*.rnc
