#!/bin/bash

[ "$(CreoleGet ad_local)" = 'oui' ] || exit 0

. /usr/lib/eole/ihm.sh

INTERNALLY_BRIDGED="$(CreoleGet ad_local_default_bridge_via_internal_ip oui)"
CMD="lxc-attach -n addc -s NETWORK -- "
LOG_CMD="systemd-cat -t ntp-packet-routing" # Les messages sont consultables avec la commande journalctl -t ntp-packet-routing

AD_HOST_IP="$(CreoleGet ad_public_address)"
MARK=123;
TABLE=123;

lxc-wait -n addc -s RUNNING

$LOG_CMD $CMD iptables -t nat -C POSTROUTING --out containers -s $AD_HOST_IP/32 -p udp --dport 123 -j SNAT --to-source 192.0.2.2
POSTROUTED=$?
$LOG_CMD $CMD iptables -t mangle -C OUTPUT -p udp --dport 123 -j MARK --set-mark $MARK
MANGLED=$?
$LOG_CMD $CMD ip route list table $TABLE
IPRULED=$?

if [ "${INTERNALLY_BRIDGED}" = "non" ]; then
    # set rules
    if [ "$POSTROUTED" -ne 0 ];then
        $LOG_CMD echo "set postrouting"
        $LOG_CMD $CMD iptables -t nat -A POSTROUTING --out containers -s $AD_HOST_IP/32 -p udp --dport 123 -j SNAT --to-source 192.0.2.2
    else
        $LOG_CMD echo "NTP packet already postrouted"
    fi
    if [ "$MANGLED" -ne 0 ];then
        $LOG_CMD echo "set packet marking"
        $LOG_CMD $CMD iptables -t mangle -A OUTPUT -p udp --dport 123 -j MARK --set-mark $MARK
    else
        $LOG_CMD echo "packet marking already set"
    fi
    if [ "$IPRULED" -ne 0 ];then
        $LOG_CMD echo "set ip rule"
        $LOG_CMD $CMD ip rule add fwmark $MARK table $TABLE;
        $LOG_CMD $CMD ip route add default via 192.0.2.1 table $TABLE;
    else
        $LOG_CMD echo "table rules already set"
    fi
else
    # clean rules
    if [ "$POSTROUTED" -eq 0 ];then
        $LOG_CMD echo "unset postrouting"
        $LOG_CMD $CMD iptables -t nat -D POSTROUTING --out containers -s $AD_HOST_IP/32 -p udp --dport 123 -j SNAT --to-source 192.0.2.2
    fi
    if [ "$MANGLED" -eq 0 ];then
        $LOG_CMD echo "unset mangle"
        $LOG_CMD $CMD iptables -t mangle -D OUTPUT -p udp --dport 123 -j MARK --set-mark $MARK
    fi
    if [ "$IPRULED" -eq 0 ];then
        $LOG_CMD echo "unset ip rule"
    fi
fi

exit 0
