#!/bin/sh

. ddns-sh-functions

### dynamic variables
ddns_serial="$(date +%Y%m%d)00"
resolvconfzone_file="$ddns_root/etc/resolvconf-zones.conf"

make_key()
{
    cd "$ddns_root/etc"

    rm -f "K$ddns_key.+157+"*
    local key="$(/usr/sbin/dnssec-keygen -r /dev/urandom -a HMAC-MD5 -b 512 -n USER "$ddns_key")"
    local secret="$(sed -n 's/Key:[[:space:]]\+\([^[:space:]]\+\)/\1/p' "$key.private")"

    cd - >/dev/null

    cat>"$ddns_root/etc/$ddns_key.conf"<<EOF
key $ddns_key {
    algorithm hmac-md5;
    secret "$secret";
};
EOF

    cat>>"$ddns_root/$ddns_zone_file"<<EOF
include "/etc/$ddns_key.conf";

EOF

}

make_include()
{
    local_file="$ddns_root/etc/local.conf"

    grep -qs "include[[:space:]]\+\"$ddns_zone_file\"[[:space:]]*;[[:space:]]*\$" "$local_file" ||
        printf 'include "%s";\n' "$ddns_zone_file" >>"$local_file"
}

make_forward_zone()
{

cat>>"$ddns_root/$ddns_zone_file"<<EOF
zone "$ddns_zone" {
    type master;
    file "$ddns_zone_dir/$ddns_zone";
    allow-update { key $ddns_key; };
    allow-transfer { localnets; };
    notify yes;
};
EOF

cat>"$ddns_root/zone/$ddns_zone_dir/$ddns_zone"<<EOF
\$TTL	1D
@	IN	SOA	$ddns_ns_record	$ddns_user_record ($ddns_serial 12H 1H 1W 1H)
	IN	NS	$ddns_ns_record
;
_kerberos._udp		IN	SRV	0	0	88	ns
_kerberos._tcp		IN	SRV	0	0	88	ns
_kerberos-adm._tcp	IN	SRV	0	0	749	ns
_kerberos		IN	TXT	$(echo $ddns_zone| tr '[[:lower:]]' '[[:upper:]]')

EOF
}

make_reverse_zone()
{
local ddns_rzone="$1.in-addr.arpa"

cat>>"$ddns_root/$ddns_zone_file"<<EOF
zone "$ddns_rzone" {
    type master;
    file "$ddns_zone_dir/$ddns_rzone";
    allow-update { key $ddns_key; };
};
EOF

cat>"$ddns_root/zone/$ddns_zone_dir/$ddns_rzone"<<EOF
\$TTL	1D
@	IN	SOA	$ddns_ns_record $ddns_user_record ($ddns_serial 12H 1H 1W 1H)
	IN	NS	$ddns_ns_record
EOF
}

has_ip || exit 0

install -d -m770 -o root -g named -- "$ddns_root/zone/$ddns_zone_dir"

#clear resolvconf zones information
if [ -f "$resolvconfzone_file" ];then
    echo "Cleaning up resolvconf zones..." >&2
    >"$resolvconfzone_file"
fi

#remove previous zone definitions
rm -f -- "$ddns_root/$ddns_zone_file"
rm -f "$ddns_root/zone/$ddns_zone_dir"/*

make_include
make_key
make_forward_zone
foreach_reverse make_reverse_zone

/usr/sbin/dhcp-reset-static

#update resolvconf zones information
if [ -f "$resolvconfzone_file" ];then
    echo "Update resolvconf zones..." >&2
    resolvconf -u
fi
