#!/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
    export dir=${dir%*/}      # remove the trailing "/"
    export netname=${dir##*/}    # print everything after the final "/"
    export config_out="/etc/lixonet/${netname}/.config"

    # 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 -rfv "$(basename "$git" .git)"
    rsa_filename="/etc/lixonet/${netname}/id_rsa"
    if [ ! -f $rsa_filename ]; then rsa_filename="/etc/lixonet/id_rsa"; fi
    echo "Using SSH key: $rsa_filename"
    GIT_SSH_COMMAND="ssh -i $rsa_filename -o IdentitiesOnly=yes" git clone $git || { echo "clone $git failed, quitting" ; exit 1; }
    
    # Clone any add-ons
    for addon_git in `echo "$addons" | tr "," "\n"`
    do
    	rm -rfv "$(basename "$addon_git" .git)"     	
	rsa_filename="/etc/lixonet/${netname}/$(basename "$addon_git" .git).key"
	if [ ! -f $rsa_filename ]; then rsa_filename="/etc/lixonet/${netname}/id_rsa"; fi
    	echo "Using SSH key: $rsa_filename"
	GIT_SSH_COMMAND="ssh -i $rsa_filename -o IdentitiesOnly=yes" git clone $addon_git || { echo "clone addon $addon_git failed, quitting" ; exit 1; }
    done
    
    echo "Creating work directory..."
    rm -rfv work
    mkdir --verbose work
    cp -rv "$(basename "$git" .git)"/* work/
    for addon_git in `echo "$addons" | tr "," "\n"`
    do
    	cp -rv "$(basename "$addon_git" .git)"/* work/
    done
    
    cd work

    # Copy default files
    mkdir --verbose tinc; cp -rv ../tinc/* tinc/
    mkdir --verbose bird; cp -rv ../bird/* bird/
    mkdir --verbose bind; cp -rv ../bind/* bind/
    if [ "${wg_enabled:-0}" -eq "1" ]; then
	mkdir --verbose wireguard; cp -rv ../wireguard/* wireguard/
    fi
    if [ "${ddns_enabled:-0}" -eq "1" ]; then
	mkdir --verbose ddns; cp -rv ../ddns/* ddns/
    fi
    
    # Copy system-local custom files (if they even exist)
    cp -rv $dir/tinc/* tinc/
    cp -rv $dir/bird/* bird/
    cp -rv $dir/bind/* bind/
    if [ "${wg_enabled:-0}" -eq "1" ]; then
	cp -rv $dir/wireguard/* wireguard/
    fi
    if [ "${ddns:-0}" -eq "1" ]; then
	cp -rv $dir/ddns/* ddns/
    fi
    
    # Tinc
    #  Remove existing configuration
    rm -v -rf $config_out/tinc/*
    #  Copy all tinc default files to /etc/(tinc)
    find tinc -type d | xargs -I '{}' mkdir --verbose -p $config_out/{}
    find tinc -type f | sed -e "s@tinc/@@g" | xargs -I '{}' cp --verbose tinc/{} $config_out/tinc/{}
    #  Build list of all peer IP addresses
    tinc_peers=$(cat $config_out/tinc/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")
    #  Copy private key
    cp -v /etc/lixonet/$netname/tinc.key $config_out/tinc/rsa_key.priv
   
    # Bird
    #  Remove existing configuration
    rm -v -rf $config_out/bird/*
    #  Copy all bird default files to /etc/(bird)
    find bird -type d | xargs -I '{}' mkdir --verbose -p $config_out/{}
    find bird -type f | sed -e "s@bird/@@g" | xargs -I '{}' cp --verbose bird/{} $config_out/bird/{}

    # BIND
    #  Remove existing configuration
    rm -v -rf $config_out/bind/*
    #  Copy all bind default files to /etc/(bind)
    find bind -type d | xargs -I '{}' mkdir --verbose -p $config_out/{}
    find bind -type f | sed -e "s@bind/@@g" | xargs -I '{}' cp --verbose bind/{} $config_out/bind/{}
	
    # Wireguard
    if [ "${wg_enabled:-0}" -eq "1" ]; then
	#  Remove existing configuration
	rm -v -rf $config_out/wireguard/*
	#  Copy all wireguard default files to /etc/(wireguard)
	find wireguard -type d | xargs -I '{}' mkdir --verbose -p $config_out/{}
	find wireguard -type f | sed -e "s@wireguard/@@g" | xargs -I '{}' cp --verbose wireguard/{} $config_out/wireguard/{}
    fi
    
    # Docker
    #  Copy templates and dependencies to directory
    mkdir docker/
    cp -rv ../docker/* docker/
    if [ "${wg_enabled:-0}" -eq "1" ]; then
	cp -v docker/services.opt/wireguard docker/services/wireguard
	cp -v docker/services.opt/wireguard_router docker/services/wireguard_router
    fi
    if [ "${ddns_enabled:-0}" -eq "1" ]; then
	cp -v docker/services.opt/ddns docker/services/ddns
    fi
    
    for addon_git in `echo "$addons" | tr "," "\n"`
    do
    	echo "Running addon script for $(basename "$addon_git" .git)..."
    	chmod +x "$(basename "$addon_git" .git).sh" && "./$(basename "$addon_git" .git).sh"
    done
    
    # Process templates
    echo "Processing configuration templates..."
    process_templates "$config_out/" "$sigil_vars"
    echo "Setting any processed shell scripts as executable..."
    find $config_out -type f -name "*.sh" | xargs -I '{}' chmod -v +x {}
    chmod -v +x $config_out/tinc/tinc-up $config_out/tinc/tinc-down $config_out/tinc/subnet-up $config_out/tinc/subnet-down $config_out/tinc/host-up $config_out/tinc/host-down $config_out/tinc/check-node
	
    cp -rv $dir/docker/* docker/
    cp -v ./../docker-compose.yml.tmpl .
    cp -v ../Dockerfile.* .
    echo "Processing Docker templates..."
    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 -v .env

    # Pop directory
    cd $topdir
done