#!/bin/bash

if [ -z ${OVERWRITE+x} ]; then 
    export OVERWRITE=0
else 
    echo OVERWRITE=$OVERWRITE;
fi

# -------------------------------------------------------- subst-and-copy-file -----
function subst-and-copy-file {
    local SRC_FILE=$1
    local DST_FILE=$2

    echo -n "$SRC_FILE >> $DST_FILE : "

    if [ -f $DST_FILE ]; then
        EXISTS=1
    else
        EXISTS=0
    fi
    
    if [[ $OVERWRITE -eq 0 && $EXISTS -eq 1 ]]; then
        echo EXISTS, skipped
    else
        cat $SRC_FILE | tr ' "' '\002\003' | while read line; do eval "echo \"$line\""; done |  tr '\002\003' ' "' > $DST_FILE
        if [ $EXISTS -eq 1 ]; then
            echo OVERWRITTEN
        else
            echo CREATED
        fi
    fi
}

# -------------------------------------------------------- subst-and-copy-tree -----
function subst-and-copy-tree {
    local SRC_DIR=$1
    local DST_DIR=$2

    for LINE in $(find $SRC_DIR |sed -n '1!p') # skip first line, it is a base directory itself
    do
        local SUFFIX=${LINE#$SRC_DIR/}
        if [ -d $LINE ]; then
            mkdir -p $DST_DIR/$SUFFIX
            echo Created directory: $SUFFIX
        elif [ -f $LINE ]; then
            subst-and-copy-file $SRC_DIR/$SUFFIX $DST_DIR/$SUFFIX
        fi
    done
}

# ------------------------------------------------------------------- load-env -----
function load-env {
    if [ -f /opt/sarch/etc/base.conf ]; then
        echo Using configuration: $(find /opt/sarch/etc/*.conf -maxdepth 1 -type f)
        export ENV_LOADER=/tmp/overcast-env                   	
        echo "#!/bin/bash" > $ENV_LOADER
        chmod +x $ENV_LOADER 
        find /opt/sarch/etc/*.conf -maxdepth 1 -type f | xargs cat |
        while read line; do
            [[ $line == \#* ]] && continue
            [[ ! $line =~ ([^[:space:]]*)=(.*) ]] && continue
            KEY=${BASH_REMATCH[1]}
            VALUE=${BASH_REMATCH[2]}
            echo export $KEY=$VALUE >> $ENV_LOADER
            echo $KEY=$VALUE
        done 
        . $ENV_LOADER
        echo
    else
        echo Missing /opt/sarch/etc/base.conf, make sure to load environment with image-conf first
        exit 1
    fi
}

export -f subst-and-copy-file
export -f subst-and-copy-tree
export -f load-env

