#!/bin/bash

source _config.in.sh

echo "#!/bin/bash"
echo "# Generated as: source _generate.in.sh > generate.sh"
echo
echo "rm -r generated/* 2>/dev/null"
echo "mkdir generated 2>/dev/null"
echo "set -e"

for SERV in ${SERVICES[@]}; do 
    >&2 echo
    >&2 echo "=== Scripting $SERV"
    echo ">&2 echo"
    echo ">&2 echo === Generate $SERV"
    echo "mkdir generated/$SERV"

    SS=${S[$SERV]}; 
    SUF_O=$(echo $SS | sed s:-none::); 
    SUF_RTY=$(echo $SS | sed s:-none:-common:); 
    for i in environment basesearch-refresh OxygenOptions.cfg rtyserver.conf; do 
        SUF=$SUF_O; [[ $i == *"rtyserver"* ]] && SUF=$SUF_RTY;
        >&2 echo "=== * $i $SUF"; 
        O=$(echo $i | sed 's:rtyserver.conf:rtyserver.conf-common:'); 
        BASE=$O; TRG="${i}${SUF}"; 
        PATCH="${TRG}_patch.json"; 
        [[ -f $BASE ]] && [[ -f $PATCH ]] && \
                echo "./config_patcher patch --ignore-prefix $BASE $PATCH $TRG"
        PATCH="${TRG}.patch"
        [[ -f $BASE ]] && [[ -f $PATCH ]] && \
                echo "patch $BASE -i $PATCH -o $TRG"
        echo "cp -v $TRG generated/${SERV}/$TRG"; 
    done; 
    i="OxygenOptionsRt.cfg"; 
    >&2 echo "=== * $i $SUF"; 
    BASE="OxygenOptions.cfg${SUF_O}"; 
    PATCH="OxygenOptionsRt.cfg.patch"; 
    TRG="${i}${SUF_O}"; 
    echo "[[ -f $BASE ]] && patch $BASE -i $PATCH -o $TRG"; echo "[[ -f $TRG ]] && cp -v $TRG generated/${SERV}/$TRG"; 
done
