#!/bin/bash

# this script automagically rebuilds pdns-secret
# with information retrieved from interfaces.
#
# the address that contains :99: is presumed to be
# the secret ip.


SOURCE=~/public_html/fulhack/pdns-secret.c
DEST=/usr/local/sbin/pdns-secret

ZONE="twilight.fatal.se"
SECRETTXT="You are about to enter another dimension. A dimension not only of sight and sound, but of mind. A journey into a wondrous land of imagination. Next stop, the Twilight Zone!"
FAKETXT="You unlock this door with the key of imagination."

function expand_short_addr
{
	_SHORTADDR=$1
	_SHORTSEP=${_SHORTADDR//[^:]/}

	if [ ${#_SHORTSEP} = 8 ]; then
		echo $_SHORTADDR
		return
	fi

	_SHORTREPL=""

	#echo "DEBUG: _SHORTSEP=$_SHORTSEP" >&2
	while [ ${#_SHORTSEP} -lt 8 ]; do
		_SHORTREPL=${_SHORTREPL}:0
		_SHORTSEP=${_SHORTSEP}:
		#echo "DEBUG: _SHORTSEP=$_SHORTSEP" >&2
	done
	_SHORTREPL=${_SHORTREPL}:

	_LONGADDR=${_SHORTADDR//::/$_SHORTREPL}


	#echo "DEBUG: _LONGADDR=$_LONGADDR" >&2

	echo $_LONGADDR
}

function reverse_secret_ip
{
	_REVZONEIP=$(expand_short_addr $1)
	#echo "DEBUG: _REVZONEIP=$_REVZONEIP::" >&2


	# get string length
	_I=${#_REVZONEIP}
	_J=0

	while [ $_I -gt 0 ]; do
		((_I--))

		# get last character.
		_X=${_REVZONEIP:${_I}:1}

		if [ "$_X" == ":" ]; then
			# pad with zeroes if needed.
			while [ $_J -lt 4 ]; do
				_REVZONE=${_REVZONE}.0
				((_J++))
			done
			# reset counter.
			_J=0
			continue
		fi

		# count characters between : and :.
		((_J++))

		# append digit.
		_REVZONE=${_REVZONE}.$_X

		#echo "DEBUG: _REVZONE=$_REVZONE" >&2
	done

	_REVZONE=${_REVZONE:1}.ip6.arpa
	#echo "DEBUG: finished _REVZONE=$_REVZONE" >&2

	echo $_REVZONE
}

SECRETIP=$(ip -6 ad sh scope global | awk '/2002:.*:99:.*/{print $2}' | cut -d / -f1 | head -n 1)

SECRETREV=$(reverse_secret_ip $SECRETIP)

echo "ZONE=$ZONE"
echo "SECRETIP=$SECRETIP"
echo "SECRETREV=$SECRETREV"


gcc "$SOURCE" -o "$DEST" "-DZONE=\"$ZONE\"" "-DSECRETREV=\"$SECRETREV\"" "-DSECRETIP=\"$SECRETIP\"" "-DSECRETTXT=\"$SECRETTXT\"" "-DFAKETXT=\"$FAKETXT\""

