#!/bin/bash
set -e

sdir=/usr/share/omix
ldir=/var/lib/omix
vdir=/etc/omix
ddir=/usr/share/doc/omix-gw
doc() {
    local vfile=$vdir/$1
    touch $vfile
    [[ -s $vfile ]] || echo $'\n' > $vfile
    local head=$(sed 's/\[/\\\[/g; s/\]/\\\]/g; s/\//\\\//g' <<< $2 )
    sed -i "1{/^${head}$/b}; 1 i $2" $vfile
}

#bak
bak="--backup=numbered"
nftconf=/etc/nftables.conf
sed -e '/^#/d' -e '/^$/d'  /etc/dnsmasq.conf | grep . && mv $bak /etc/dnsmasq.conf /etc/dnsmasq.conf.dpkg-old
sed -i -e 's?^CONFIG_DIR=.*$?CONFIG_DIR=/etc/dnsmasq.d,\*.conf?' /etc/default/dnsmasq
[[ ( -e $nftconf || -L $nftconf ) && $(readlink $nftconf || :) != $ldir/nftables.rt ]] \
  && mv $bak $nftconf $nftconf.dpkg-old

#conf
[[ -e $ldir/nftables.conf ]] || cp $ddir/nftables.conf.sample $ldir/nftables.conf
doc dns.server '# /<domain>/<ip>'
doc dns.rev '# <cidr>,<ip>'
doc nft.port_forward '# description proto port target[:port] [from address]'

#ln
for f in dhcp.conf dnsmasq.conf servers; do
  [ -L /etc/dnsmasq.d/$f ] || ln -s $ldir/$f /etc/dnsmasq.d/$f
done
[ -L /etc/nftables.conf ] || ln -s $ldir/nftables.rt /etc/nftables.conf
#sys
systemctl enable nftables
/usr/share/omix/mkconf

