#!/bin/ash

topdir=`pwd`

for dir in `find /etc/lixonet/* -type d -maxdepth 0`
do
    echo "Inspecting $dir..."

    dir=${dir%*/}      # remove the trailing "/"
    netname=${dir##*/}    # print everything after the final "/"

    # Load relevant environment variables from lixonet.conf
    unset git
    source $dir/lixonet.conf
    if [ -z "$git" ]; then echo "Missing 'git' variable in $dir/lixonet.conf"; exit 1; fi

    echo "Configuring Lixonet3 network $netname from $git..."

    # Clone and enter the repository
    rm -rf "$(basename "$git" .git)"
    git clone $git
    cd "$(basename "$git" .git)"

    # Copy default files
    cp -r ../tinc/* tinc/
    cp -r ../bird/* bird/

    # Tinc
    #  Remove existing configuration
    rm -v -rf /etc/tinc/$netname/*
    #  Copy all tinc default files to /etc/(tinc)
    find tinc -type d | sed -e "s@tinc@tinc/${netname}@g" | xargs -I '{}' mkdir --verbose -p /etc/{}
    find tinc -type f | sed -e "s@tinc/@@g" | xargs -I '{}' cp --verbose tinc/{} /etc/tinc/$netname/{}
    #  Fill out templates and remove them after
    find /etc/tinc/$netname/ -type f -name '*.tmpl' -exec sh -c 'sigil -f {} -p $(cat /etc/lixonet/$netname/lixonet.conf | tr "\\n" " ") > "$(dirname {})/$(basename {} .tmpl)"' {} \;
    find /etc/tinc/$netname/ -type f -name '*.tmpl' | xargs -I '{}' rm -f {}
    #  Copy private key
    cp /etc/lixonet/$netname/tinc.key /etc/tinc/$netname/rsa_key.priv
    #  Set permissions for tinc scripts
    chmod +x /etc/tinc/$netname/tinc-up
    chmod +x /etc/tinc/$netname/tinc-down
    chmod +x /etc/tinc/$netname/subnet-up
    chmod +x /etc/tinc/$netname/subnet-down

    # Bird
    #  Remove existing configuration
    rm -v -rf /etc/bird/$netname/*
    #  Copy all tinc default files to /etc/(bird)
    find bird -type d | sed -e "s@bird@bird/${netname}@g" | xargs -I '{}' mkdir --verbose -p /etc/{}
    find tinc -type f | sed -e "s@bird/@@g" | xargs -I '{}' cp --verbose bird/{} /etc/bird/$netname/{}
    #  Fill out templates and remove them after
    find /etc/bird/$netname/ -type f -name '*.tmpl' -exec sh -c 'sigil -f {} -p $(cat /etc/lixonet/$netname/lixonet.conf | tr "\\n" " ") > "$(dirname {})/$(basename {} .tmpl)"' {} \;
    find /etc/bird/$netname/ -type f -name '*.tmpl' | xargs -I '{}' rm -f {}

    #docker-compose up -d --build

    # Pop directory
    cd $topdir
done