#!/bin/bash


[ "$LXC_NETWORK" ] || {
    echo "You must set \$LXC_NETWORK (to something like 172.160.0 ) before using this script."
    exit 1
}

HOST_EXTERNAL_DEVICE=${HOST_EXTERNAL_DEVICE:-eth0}

apt-get install -y bind9 dnsmasq bind9-host </dev/null

echo HOST_EXTERNAL_DEVICE="$HOST_EXTERNAL_DEVICE" >> /etc/default/lxc
sed -ri "s%10\.0\.3\.%$LXC_NETWORK.%g;s%^#LXC_DHCP_CONFILE=%LXC_DHCP_CONFILE=%g" /etc/default/lxc-net

LXC_ADDR=$(. /etc/default/lxc && echo "$LXC_ADDR")
if [ -z "$LXC_ADDR" ]; then
    LXC_ADDR=$(. <(cat /usr/lib/x86_64-linux-gnu/lxc/lxc-net | grep ^LXC_ADDR | head -n 1) && echo "$LXC_ADDR")
fi

HOST_IP=$(. /etc/default/lxc && ifip "$HOST_EXTERNAL_DEVICE")

echo "
server=$LXC_ADDR
interface=lo
bind-interfaces
no-negcache
log-queries
log-facility=/var/log/dnsmasq.log
" >> /etc/dnsmasq.conf

echo "
server=${HOST_IP}
bind-interfaces
log-queries
no-negcache
log-facility=/var/log/lxc-dnsmasq.log
no-resolv
" >> /etc/lxc/dnsmasq.conf

(
  cp "src/etc/bind/named.conf.options" "/etc/bind/named.conf.options" &&
  sed -ri "s/%%EXTERNAL_IP%%/$HOST_IP/g" "/etc/bind/named.conf.options"
)
## XXXvlab: Maybe we could change this in the service start/stop of the named daemon

mkdir /var/log/named -p &&
chown bind:bind /var/log/named

/etc/init.d/bind9 stop
/etc/init.d/dnsmasq stop

service lxc restart
service lxc-net restart  ## had to 'brctl delbr lxcbr0' myself

/etc/init.d/dnsmasq start
/etc/init.d/bind9 start

cp /etc/resolv.conf{,.orig}
cat <<EOF > /etc/resolv.conf
nameserver 127.0.0.1
EOF

##
## Logrotate for dnsmasq and named
##

cat <<EOF >  /etc/logrotate.d/dnsmasq

/var/log/dnsmasq.log {
       missingok
       copytruncate
       notifempty
       compress

       postrotate
           /bin/kill -s SIGUSR2 "\$(cat /var/run/dnsmasq/dnsmasq.pid)"
       endscript
}

EOF


cat <<EOF >  /etc/logrotate.d/lxc-dnsmasq

/var/log/lxc-dnsmasq.log {
       missingok
       copytruncate
       notifempty
       compress

       postrotate
           /bin/kill -s SIGUSR2 "\$(cat /var/run/lxc/dnsmasq.pid)"
       endscript
}

EOF

cat <<EOF > /etc/logrotate.d/named
/var/log/named/*.log {
       missingok
       copytruncate
       notifempty
       compress
}
EOF

##
## Testing
##

# lsof -i4tcp:53 -n
# netstat -ltnp  | grep :53
# ping HOST
# host HOST
# tcpdump