#!/bin/sh

TINCNAME=`uname -n`
TINCADDR=''

TINCCACHE="/etc/tinc/configure.cache"

if test -e "$TINCCACHE"
then
	. "$TINCCACHE"
fi

cat <<EOF
######################################
# tinc Konfigurationsskript von octo #
######################################

EOF

echo -n "Name [$TINCNAME]: "
read foo
if test "x$foo" != "x"
then
	TINCNAME="$foo"
fi
if test "x$TINCNAME" = "x"
then
	echo "Kein Hostname angegeben." >&2
	exit 1
fi

echo -n "IP-Adresse [$TINCADDR]: "
read foo
if test "x$foo" != "x"
then
	TINCADDR="$foo"
fi
if test "x$TINCADDR" = "x"
then
	echo "Keine IP-Adresse angegeben." >&2
	exit 1
fi

cat <<EOF

Konfigurationsparameter:

  Hostname:   $TINCNAME
  IP-Adresse: $TINCADDR
  
EOF
echo -n "Angaben korrekt [ja]: "
read foo
if test "x$foo" = "x" || test "x$foo" = "xj" || test "x$foo" = "xy" || test "x$foo" = "xja" || test "x$foo" = "xyes"
then
	cat <<EOF >"$TINCCACHE"
TINCNAME="$TINCNAME"
TINCADDR="$TINCADDR"
EOF
else
	exit 0
fi

for FILE in freifunk/tinc.conf freifunk/tinc-up
do
	echo -n "Generiere $FILE... "
	sed -e "s/@TINCNAME@/$TINCNAME/g" -e "s/@TINCADDR@/$TINCADDR/g" <"$FILE.in" >"$FILE"
	echo "fertig"
done

echo -n "Anpassen der Berechtigungen... "
chmod 0775 freifunk/tinc-up
chmod 0775 freifunk/tinc-down
echo "fertig"

if test ! -e "/etc/tinc/freifunk/hosts/$TINCNAME"
then
	echo "Die Datei /etc/tinc/freifunk/hosts/$TINCNAME existiert nicht."
	tincd -K -n freifunk
	cat <<EOF
	
Bitte veroeffentliche deinen oeffentlichen Schluessel im Wiki:
 http://freifunk-franken.de/vpn#wlan-router
-- 8< --
# Name: $TINCNAME / $TINCADDR
# User: 
# Standort: 
EOF
	cat "/etc/tinc/freifunk/hosts/$TINCNAME"
	cat <<EOF
-- >8 --

EOF
fi

if test -e "/var/run/tinc.freifunk.pid"
then
	TINCPID=`cat /var/run/tinc.freifunk.pid`
	echo -n "Beende tinc Prozess $TINCPID... "
	kill $TINCPID
	sleep 1
	echo "fertig"
fi

echo -n "Starte tinc Prozess... "
tincd -n freifunk
echo "fertig"

cat <<EOF

Ich habe fertig! Viele Spaesse!
                           -octo
EOF

exit 0
