#!/bin/ash

# https://stackoverflow.com/questions/3474526/stop-on-first-error
# http://web.archive.org/web/20110314180918/http://www.davidpashley.com/articles/writing-robust-shell-scripts.html
set +e

process_template ( ) {
    processed_filename=$(dirname $1)/$(basename $1 .tmpl)
    echo "Processing template $1 -> $processed_filename"
	set -e
    sh -c "sigil -f $1 -p $2 > $processed_filename"
	set +e
    rm $1
}

function join_by { local IFS="$1"; shift; echo "$*"; }

process_templates ( ) {
for template_filename in `find $1 -type f -name '*.tmpl'`
do
    process_template $template_filename "$2"
done
}

topdir=`pwd`

for dir in `find /etc/lixonet/* -type d -maxdepth 0`
do
    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
    sigil_vars=$(cat /etc/lixonet/${netname}/lixonet.conf | tr "\\n" " ")
    sigil_vars=$(echo "$sigil_vars netname=$netname")

    # Parse subnets into a collection of IP reverse zones
    root_reverse_zones=$(echo '${network_address}/${global_prefix:-16}' | sigil -p $sigil_vars | xargs -I '{}' netcalc split {} 24 | sed 's/.0\/24$//' | awk 'BEGIN{FS="."}{print $3"."$2"."$1".in-addr.arpa"}' | sed -e ':a;N;$!ba;s/\n/,/g')
    sigil_vars=$(echo "$sigil_vars root_reverse_zones=$root_reverse_zones")
    local_reverse_zones=$(echo "$bgp_routes" | tr "," "\n" | xargs -I '{}' netcalc split {} 24 | sed 's/.0\/24$//' | awk 'BEGIN{FS="."}{print $3"."$2"."$1".in-addr.arpa"}' | sed -e ':a;N;$!ba;s/\n/,/g')
    sigil_vars=$(echo "$sigil_vars local_reverse_zones=$local_reverse_zones")

    echo "Configuring Lixonet3 network $netname from $git..."
    echo "Variables: $sigil_vars"

    # Clone and copy the repository
    rm -rf "$(basename "$git" .git)"
    GIT_SSH_COMMAND="ssh -i /etc/lixonet/${netname}/id_rsa -o IdentitiesOnly=yes" git clone $git || { echo "clone $git failed, quitting" ; exit 1; }
    echo "Creating work directory..."
    rm -rf work
    mkdir --verbose work
    cp -r "$(basename "$git" .git)"/* work/ && cd work

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

    # Copy system-local custom files (if they even exist)
    cp -r $dir/tinc/* tinc/
    cp -r $dir/bird/* bird/
    cp -r $dir/bind/* bind/

    # 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/{}
    #  Build list of all peer IP addresses
    tinc_peers=$(cat /etc/tinc/$netname/hosts/* | grep 'Subnet' | grep '/32' | grep -oE '((1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])' | sed -e ':a;N;$!ba;s/\n/,/g')
    sigil_vars=$(echo "$sigil_vars tinc_peers=$tinc_peers")
    #  Fill out templates and remove them after
    process_templates "/etc/tinc/$netname/" "$sigil_vars"
    #  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 /etc/tinc/$netname/tinc-down /etc/tinc/$netname/subnet-up /etc/tinc/$netname/subnet-down

    # Bird
    #  Remove existing configuration
    rm -v -rf /etc/bird/$netname/*
    #  Copy all bird default files to /etc/(bird)
    find bird -type d | sed -e "s@bird@bird/${netname}@g" | xargs -I '{}' mkdir --verbose -p /etc/{}
    find bird -type f | sed -e "s@bird/@@g" | xargs -I '{}' cp --verbose bird/{} /etc/bird/$netname/{}
    #  Fill out templates and remove them after
    process_templates "/etc/bird/$netname/" "$sigil_vars"

    # BIND
    #  Remove existing configuration
    rm -v -rf /etc/bind/$netname/*
    #  Copy all bind default files to /etc/(bind)
    find bind -type d | sed -e "s@bind@bind/${netname}@g" | xargs -I '{}' mkdir --verbose -p /etc/{}
    find bind -type f | sed -e "s@bind/@@g" | xargs -I '{}' cp --verbose bind/{} /etc/bind/$netname/{}
    #  Fill out templates and remove them after
    process_templates "/etc/bind/$netname/" "$sigil_vars"
    
    # Docker
    #  Copy templates and dependencies to directory
    mkdir docker/
    cp -r ../docker/* docker/
    cp -r $dir/docker/* docker/
    cp ./../docker-compose.yml.tmpl .
    cp ../Dockerfile.* .
    process_templates "." "$sigil_vars"

    echo $sigil_vars | tr ' ' '\n' > .env
    cat docker-compose.yml
	
	set -e
    docker-compose -p $netname down
    docker-compose -p $netname up -d --build --remove-orphans
	set +e
	
    rm .env

    # Pop directory
    cd $topdir
done