## Launch Tayga within a container


# Enable Forwarding
echo "Enabling IPv4 and IPv6 forwarding"
echo 1 > /proc/sys/net/ipv4/conf/all/forwarding
echo 1 > /proc/sys/net/ipv6/conf/all/forwarding

# Default environment variables
TAYGA_PREF64="${TAYGA_PREF64:-64:ff9b::/96}"
TAYGA_POOL4="${TAYGA_POOL4:-192.168.240.0/20}"
TAYGA_WKPF_STRICT="${TAYGA_WKPF_STRICT:-no}"

# Auto-detect ADDR4 and ADDR6 from the container if not set
echo Finding Addr4
if [[ -z "${TAYGA_ADDR4}" ]]; then
    IF4=$(ip -o -4 route show to default | awk '{print $5}')
    ADDR4=$(ip addr show ${IF4} | grep -E 'inet ' | awk '{print $2}' | cut -d'/' -f1 | head -n 1)
    if [[ -z "${ADDR4}" ]]; then
        echo "No IPv4 address found on iface ${IF4}, exiting"
        exit 1
    fi
    TAYGA_ADDR4="${ADDR4}"
    echo Using Container Addr4 $TAYGA_ADDR4 from ${IF4}
fi
echo Finding Addr6
if [[ -z "${TAYGA_ADDR6}" ]]; then
    IF6=$(ip -o -6 route show to default | awk '{print $5}')
    ADDR6=$(ip addr show ${IF6} | grep -E 'inet6 ' | awk '{print $2}' | cut -d'/' -f1 | head -n 1)
    if [[ -z "${ADDR6}" ]]; then
        echo "No IPv6 address found on iface ${IF6}, exiting"
        exit 1
    fi
    TAYGA_ADDR6="${ADDR6}"
    echo Using Container Addr6 $TAYGA_ADDR6 from ${IF6}
fi
if [[ -z "${TAYGA_MTU}" ]]; then
    IF6=$(ip -o -6 route show to default | awk '{print $5}')
    MTU=$(ip link show ${IF6} | grep -E 'mtu ' | awk '{print $5}')
    if [[ -z "${MTU}" ]]; then
        echo "No MTU found for iface ${IF6}, exiting"
        exit 1
    fi
    TAYGA_MTU="${MTU}"
    echo Using Container MTU $TAYGA_MTU
fi

# Generate tayga.conf file
cat << EOF > /app/tayga.conf.gen
# tayga.conf
# This file is generated by launch-nat64.sh

tun-device nat64
wkpf-strict ${TAYGA_WKPF_STRICT}
ipv4-addr ${TAYGA_ADDR4}
ipv6-addr ${TAYGA_ADDR6}
prefix ${TAYGA_PREF64}
dynamic-pool ${TAYGA_POOL4}
data-dir /app/
EOF

# If tayga.conf does not already exist, use our new conf
if test -f /app/tayga.conf; then
    echo "tayga.conf already exists, not overwriting"
else
    echo "tayga.conf does not exist, creating it from environment variables"
    mv /app/tayga.conf.gen /app/tayga.conf
fi

# Make tunnel adapter
echo "Creating tunnel adapter"
/app/tayga -c /app/tayga.conf -d --mktun || exit 1

# Bring up the interface
echo "Bringing up the interface"
ip link set dev nat64 up
ip link set nat64 mtu ${TAYGA_MTU}
ip route add ${TAYGA_POOL4} dev nat64
ip route add ${TAYGA_PREF64} dev nat64

# Start tayga
echo "Starting tayga"
# Use debug mode instead of syslog since containers log to stdout
/app/tayga -c /app/tayga.conf -d

# Delete tunnel adapter on exit
echo "Deleting tunnel adapter on exit"
ip link del nat64