#!/bin/bash

IFCONFIG=`which ifconfig`
# subnet
INETP=`$IFCONFIG|grep inet6|grep \:\:2\/|cut -d\: -f2-5|cut -d" " -f2`
# subnet-mask
PRE="64"
# first v6
START=3
# last v6
END=10
# server-defined v6
SERVER_LIMIT=10
# interface
INT_IF="eth0"
# dbispconfig
DB=dbispconfig
# mysql
MYSQL_BIN=`which mysql`

# set ip-range
# get defined IPv6 from ispconfig
ispc_range=`/usr/bin/mysql dbispconfig -e "SELECT count(*) FROM server_ip where server_id = (select server_id from server where server_name like 'mx03%') and ip_type = 'IPv6' ORDER BY ip_address;"|grep -v count`
ip_range=$(($END - $START))
# add IPv6 form ispcongig and server-ip-limit to ip-range
ip_range=$(($ip_range + $SERVER_LIMIT + $ispc_range))

# check and set IPv6-Limit
max_INT_IF=`cat /proc/sys/net/ipv6/conf/$INT_IF/max_addresses`
max_DEFAULT=`cat /proc/sys/net/ipv6/conf/default/max_addresses`
max_ALL=`cat /proc/sys/net/ipv6/conf/all/max_addresses`
if [ $max_INT_IF -lt $ip_range ]; then echo $ip_range > /proc/sys/net/ipv6/conf/$INT_IF/max_addresses; fi
if [ $max_DEFAULT -lt $ip_range ]; then echo $ip_range > /proc/sys/net/ipv6/conf/default/max_addresses; fi
if [ $max_ALL -lt $ip_range ]; then echo $ip_range > /proc/sys/net/ipv6/conf/all/max_addresses; fi

echo "Adding IPv6 Alias..."
for i in `seq $START $END`; do
  if [ $i -lt 9999 ]
    then $IFCONFIG $INT_IF inet6 add ${INETP}::${i}/${PRE}
    else 
      hex=`printf "%x\n" $i`
      $IFCONFIG $INT_IF inet6 add ${INETP}::${hex}/${PRE}
  fi
done

# get IPv6 from dbispconfig
echo -n "Adding IPv6 from ISPConfig..."
$MYSQL_BIN $DB -e "SELECT ip_address FROM server_ip where server_id = (select server_id from server where server_name like '`hostname`%') and ip_type = 'IPv6' ORDER BY ip_address ASC;" | grep -v 'ip_address' | while read IPv6; do
  $IFCONFIG $INT_IF inet6 add ${IPv6}/${PRE}
done

echo "Done!"


