#!/bin/bash

SRV=$1
if [ -z "$SRV" ]; then
    echo "usage: $0 machine"
    exit 1
fi

dirname="/var/lib/risotto/templates/$SRV"
if [ ! -d "$dirname" ]; then
    echo "cannot find $dirname"
    echo "usage: $0 machine"
    exit 1
fi
cd $dirname
find -type f -not -path "./secrets/*" -not -path "./tmpfiles.d/*" -not -path "./sysusers.d/*" -not -path "./systemd/*" -not -path "./tests/*" -not -path "./etc/pki/*" | while read a; do
    machine_path="/var/lib/machines/$SRV"
    cfile="$machine_path/usr/share/factory/$a"
    if [ -f "$cfile" ]; then
        diff -u "$dirname/$a" "$cfile"
    else
        FIRST_LINE="$(head -n 1 $a)"
        if [[ "$FIRST_LINE" == "#RISOTTO: file://"* ]]; then
            other=${FIRST_LINE:16}
            diff -u "$dirname/$a" "$machine_path$other"
        elif [[ "$FIRST_LINE" == "#RISOTTO: https://"* ]]; then
            other=${FIRST_LINE:10}
            echo $other
            wget -q $other -O /tmp/template.tmp
            diff -u "$dirname/$a" /tmp/template.tmp
        elif [ ! "$FIRST_LINE" = "#RISOTTO: do not compare" ]; then
            echo "cannot find \"$cfile\" ($dirname/$a)"
        fi
    fi
done
cd - > /dev/null