#!/bin/bash
VERSION="0.1"

TIMEOUT=180
INCR=0
echo -n Waiting for libvirtd to start
while ! service libvirtd status >/dev/null 2>&1 && [ $INCR -lt $TIMEOUT ]; do
	echo -n .
	sleep 1
	INCR=$(($INCR+1))
done
echo 
service libvirtd status >/dev/null 2>&1 || (echo Livirtd failed to start. Exiting.)

setup_network() {
if [ -f /root/setup-defaults.cfg ]; then
	. /root/setup-defaults.cfg
fi

virsh net-destroy default
virsh net-undefine default

if [ "$NEWHOSTNAME" = "" -a "$IPV4" = "" -a "$IPV6" = "" ]; then
dialog --yesno " ==== DANGEROUS ==== \n\n Spoustet pouze pokud vite, co delate...\npokracovat v nastaveni site?" 0 0
if [ $? -eq 1 ]; then
	echo "Cancel pressed."; exit 
fi

NEWHOSTNAME=$(dialog --title --stdout "HOSTNAME" --inputbox "Zadejte hostname:" 8 50 `hostname`) 
if [ $? -eq 1 ]; then
	echo "Cancel pressed."; exit 
fi

service network stop
ifup bond0

ERR=1
while [ $ERR -eq 1 ]; do
	dhclient -x ; dhclient -1 -timeout 5 bond0 >/dev/null
	if [ $? -ne 0 ] ; then
			dialog --yesno " ==== CHYBA ==== \n\n Nepodarilo se ziskat adresu z DHCP. \nZkusit znovu?" 0 0
			if [ $? -eq 1 ]; then
				echo "Cancel pressed."; break 
			fi
	else
		dialog --infobox "DHCP nastaveno..." 3 34
		ERR=0
		sleep 1
	fi
done

IPV4=`host -i $NEWHOSTNAME | grep 'has address' | awk '{print $4}'`
IPV6=`host -i $NEWHOSTNAME | grep 'has IPv6 address' | awk '{print $5}'`
else
	ifup bond0
fi

VLANS="100 101 102 103 104 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010"
CFG_DIR="/etc/sysconfig/network-scripts/"
export COLLECTD_SERVER="2a03:b780:1:1:216:3eff:fe00:534"
if echo $NEWHOSTNAME | grep coh->/dev/null; then
	export HOUSING_NAME=coh
	export IF_NAME=bond0.3
	export IF_IPV6=vbr101
	export IF_MANAGE=vbr101
  export COLLECTD_SERVER="89.187.138.254"
elif echo $NEWHOSTNAME | grep slo->/dev/null; then
  export VLANS="258 271 275 1101 2001 226 245 285 286 288 289 345 6 77 294 $VLANS"
	export HOUSING_NAME=slovanet
	export IF_NAME=bond0.263
	export IF_IPV6=none
	export IF_MANAGE=vbr100
	export COLLECTD_SERVER="172.18.0.251"
elif echo $NEWHOSTNAME | grep atcdc->/dev/null; then
  export VLANS="245 246 $VLANS"
	export HOUSING_NAME=atcdc
	export IF_NAME=vbr246
	export IF_IPV6=none
	export IF_MANAGE=vbr246
	export COLLECTD_SERVER="10.134.16.200"
elif echo $NEWHOSTNAME | grep sh->/dev/null; then
  export VLANS="$VLANS"
	export HOUSING_NAME=sh
	export IF_NAME=bond0.3
	export IF_IPV6=none
	export IF_MANAGE=bond0.3
	export COLLECTD_SERVER="10.1.191.254"
elif echo $NEWHOSTNAME | grep fas->/dev/null; then
  export VLANS="2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199"
	export HOUSING_NAME=fas
	export IF_NAME=vbr2150
	export IF_IPV6=none
	export IF_MANAGE=vbr2150
	export COLLECTD_SERVER="10.1.63.254"
elif echo $NEWHOSTNAME | grep stc->/dev/null; then
  export VLANS="2705 2093 $VLANS"
	export HOUSING_NAME=stc
	export IF_NAME=vbr2093
	export IF_IPV6=none
	export IF_MANAGE=vbr2093
	export COLLECTD_SERVER="10.1.127.254"
else
  export VLANS="3006 $VLANS"
	export HOUSING_NAME=h90
	export IF_NAME=bond0.3
	export IF_IPV6=bond0.3
	export IF_MANAGE=vbr100
fi

CFG_NAME=ifcfg-$IF_NAME
####### DNS #############
echo "Writing DNS configuration"
if [ $HOUSING_NAME = coh ]; then
	cat > /etc/resolv.conf << EOF
search hosting90.cz
nameserver 87.236.197.113
nameserver 87.236.198.210
options rotate timeout:2 attempts:3
EOF
  echo "allow ^89\.187\.128\.37$" >> /etc/munin/munin-node.conf
elif [ $HOUSING_NAME = slovanet ]; then
	echo -e "search hosting90.cz\nnameserver 172.18.0.254\noptions rotate timeout:2 attempts:3" > /etc/resolv.conf
elif [ $HOUSING_NAME = atcdc ]; then
	echo -e "search hosting90.cz\nnameserver 10.134.16.254\noptions rotate timeout:2 attempts:3" > /etc/resolv.conf
elif [ $HOUSING_NAME = sh ]; then
	echo -e "search hosting90.cz\nnameserver 10.134.72.254\noptions rotate timeout:2 attempts:3" > /etc/resolv.conf
elif [ $HOUSING_NAME = fas ]; then
	echo -e "search hosting90.cz\nnameserver 8.8.8.8\noptions rotate timeout:2 attempts:3" > /etc/resolv.conf
elif [ $HOUSING_NAME = stc ]; then
	echo -e "search hosting90.cz\nnameserver 8.8.8.8\noptions rotate timeout:2 attempts:3" > /etc/resolv.conf
else
	echo -e "search hosting90.cz\nnameserver 130.193.9.36\nnameserver 130.193.9.46\noptions rotate timeout:2 attempts:3" > /etc/resolv.conf
fi

#######  LIBVIRT VLAN IFACES ########
echo -n "Creating vlan bridges for shared networks: "
for VLAN in $VLANS ;do
  cat > /tmp/iface.xml <<EOF
<interface type='bridge' name='vbr${VLAN}'>
  <start mode='onboot'/>
  <mtu size='1500'/>
  <bridge stp='off' delay='0'>
    <interface type='ethernet' name='bond0.${VLAN}'>
      <start mode='onboot'/>
      <vlan tag='${VLAN}'>
        <interface name='bond0'/>
      </vlan>
    </interface>
  </bridge>
</interface> 
EOF
  echo -n "$VLAN "
  virsh iface-define /tmp/iface.xml
  echo "VLAN=yes" >> /etc/sysconfig/network-scripts/ifcfg-bond0.$VLAN
#  virsh iface-start vbr${VLAN}
done
cat > /tmp/iface.xml <<EOF
<interface type='ethernet' name='bond0.3'>
  <start mode='onboot'/>
  <vlan tag='3'>
    <interface name='bond0'/>
  </vlan>
</interface>
EOF
virsh iface-define /tmp/iface.xml
echo "VLAN=yes" >> /etc/sysconfig/network-scripts/ifcfg-bond0.3
echo "MTU=1500" >> /etc/sysconfig/network-scripts/ifcfg-bond0.3
rm -f /tmp/iface.xml
if [ $HOUSING_NAME = slovanet ]; then
	cat > /tmp/iface.xml <<EOF
	<interface type='ethernet' name='bond0.263'>
	  <start mode='onboot'/>
	  <vlan tag='3'>
	    <interface name='bond0'/>
	  </vlan>
	</interface>
EOF
	virsh iface-define /tmp/iface.xml
	echo "VLAN=yes" >> /etc/sysconfig/network-scripts/ifcfg-bond0.263
	echo "MTU=1500" >> /etc/sysconfig/network-scripts/ifcfg-bond0.263
	rm -f /tmp/iface.xml
fi
echo -n "$VLAN "
#######      DEFINICE NETWORK #########
# IPV4 address
# IPV6 ADDRESS
dialog --infobox "Processing, please wait" 3 34 
if [ "$UNATTENDED" = "" -o "$IPV4" = "" ]; then
	IPV4=$(dialog --title --stdout "IPV4" --inputbox "Zadejte IPV4 adresu:" 8 50 $IPV4) 
	if [ $? -eq 1 ]; then
		echo "Cancel pressed."; exit 
	fi
fi
dialog --infobox "Processing, please wait" 3 34 
if [ "$UNATTENDED" = "" -o "$IPV6" = "" ]; then
	IPV6=$(dialog --title --stdout "IPV6" --inputbox "Zadejte IPV6 adresu:" 8 50 $IPV6) 
fi
if echo $IPV4 | grep 89.187.143 >/dev/null; then
	IPV4_GW=89.187.142.1
	IPV4_NETMASK=255.255.254.0
elif echo $IPV4 | grep 89.187.138 >/dev/null; then
	IPV4_GW=89.187.138.129
	IPV4_NETMASK=255.255.255.128
elif echo $IPV4 | grep 172.18.0. >/dev/null; then
	IPV4_GW=172.18.0.254
  IPV4_NETMASK=255.255.255.0
elif echo $IPV4 | grep 10.134.16. >/dev/null; then
	IPV4_GW=10.134.16.254
  IPV4_NETMASK=255.255.255.0
elif echo $IPV4 | grep 10.134.72. >/dev/null; then
	IPV4_GW=10.134.72.254
  IPV4_NETMASK=255.255.255.0
elif echo $IPV4 | grep 217.145.205. >/dev/null; then
	IPV4_GW=217.145.205.65
  IPV4_NETMASK=255.255.255.192
elif echo $IPV4 | grep 130.185.183. >/dev/null; then
	IPV4_GW=130.185.183.1
	IPV4_NETMASK=255.255.255.0
elif echo $IPV4 | grep 86.49.171. >/dev/null; then
	IPV4_GW=86.49.171.1
 	IPV4_NETMASK=255.255.255.0
elif echo $IPV4 | grep 213.81.195. >/dev/null; then
	IPV4_GW=213.81.195.177
 	IPV4_NETMASK=255.255.255.240
elif echo $IPV4 | grep 130.193.9. >/dev/null; then
	IPV4_GW=130.193.9.254
	IPV4_NETMASK=255.255.255.128
else
	IPV4_GW=130.193.8.254
	IPV4_NETMASK=255.255.255.128
fi

if echo $IPV6 | grep 2a01:5f0:c001:122 >/dev/null; then
	IPV6_GW=2a01:5f0:c001:122::1
elif echo $IPV6 | grep 2001:1528:124:6: >/dev/null; then
	IPV6_GW=2001:1528:124:6:ffff:ffff:ffff:ffff
else
	IPV6_GW=2a03:b780:0:200:ffff:ffff:ffff:ffff
fi

[ "$UNATTENDED" != "" ] || dialog --title "Confirmation" --yesno "Ulozit stavajici konfiguraci site?" 0 0
case $? in
0)
dialog --infobox "Zastavuji sit..." 3 34 
/etc/init.d/network stop
sleep 1
 cat > /etc/sysconfig/network << EOF
NETWORKING=yes
HOSTNAME=$NEWHOSTNAME
EOF
cat > /etc/hostname << EOF
$NEWHOSTNAME
EOF
hostname $NEWHOSTNAME
  cat >> ${CFG_DIR}ifcfg-${IF_NAME} << EOF
BOOTPROTO=static
IPADDR=$IPV4
NETMASK=$IPV4_NETMASK
GATEWAY=$IPV4_GW
EOF
if [ ${IF_IPV6} != none ]; then
	cat >> ${CFG_DIR}ifcfg-${IF_IPV6} <<-EOF
	IPV6INIT=yes
	IPV6ADDR=$IPV6
	IPV6PREFIX=64
	IPV6_AUTOCONF=no
	IPV6_DEFAULTGW=$IPV6_GW
EOF
fi
[ "$UNATTENDED" = "" ] &&  dialog --exit-label "Ok" --textbox  ${CFG_DIR}${CFG_NAME} 0 0
INCREMENT=`echo $NEWHOSTNAME | egrep -o '^h90-vh[0-9]+' | awk -F- '{print $2}' | awk -F. '{print $1}' | egrep -o '[0-9]+'`
if [ ${#INCREMENT} -ne 0 ]; then
	BACKBONE=10.0.0.$INCREMENT
	cat >> /etc/sysconfig/network-scripts/ifcfg-bond0.2 <<-EOF
	IPADDR=$BACKBONE
	NETMASK=255.255.192.0
EOF
	for i in {1..250}; do echo -e "10.0.0.$i\th90-vh$i"; done >> /etc/hosts
fi
INCREMENT=`echo $NEWHOSTNAME | egrep -o '^hc-vh[0-9]+' | awk -F- '{print $2}' | awk -F. '{print $1}' | egrep -o '[0-9]+'`
if [ ${#INCREMENT} -ne 0 ]; then
	BACKBONE=10.0.2.$INCREMENT
	cat >> /etc/sysconfig/network-scripts/ifcfg-bond0.2 <<-EOF
	IPADDR=$BACKBONE
	NETMASK=255.255.192.0
EOF
	for i in {1..250}; do echo -e "10.0.2.$i\thc-vh$i"; done >> /etc/hosts
fi
INCREMENT=`echo $NEWHOSTNAME | egrep -o '^coh-vh[0-9]+' | awk -F- '{print $2}' | awk -F. '{print $1}' | egrep -o '[0-9]+'`
if [ ${#INCREMENT} -ne 0 ]; then
	BACKBONE=10.0.64.$INCREMENT
	cat >> /etc/sysconfig/network-scripts/ifcfg-bond0.2 <<-EOF
	IPADDR=$BACKBONE
	NETMASK=255.255.192.0
EOF
	for i in {1..250}; do echo -e "10.0.64.$i\tcoh-vh$i"; done >> /etc/hosts
fi
INCREMENT=`echo $NEWHOSTNAME | egrep -o '^slo-vh[0-9]+' | awk -F- '{print $2}' | awk -F. '{print $1}' | egrep -o '[0-9]+'`
if [ ${#INCREMENT} -ne 0 ]; then
  BACKBONE=10.0.128.$INCREMENT
  cat >> /etc/sysconfig/network-scripts/ifcfg-bond0.2 <<-EOF
	IPADDR=$BACKBONE
	NETMASK=255.255.192.0
EOF
for i in {1..250}; do echo -e "10.0.128.$i\tslo-vh$i"; done >> /etc/hosts
	cat >> /etc/sysconfig/network-scripts/ifcfg-bond0.3 <<-EOF
	DEVICE=bond0.3
	ONBOOT=yes
	VLAN=yes
	MTU=1500
	IPV6INIT=no
	IPV6PREFIX=64
	IPV6_AUTOCONF=no
	BOOTPROTO=static
	IPADDR=172.18.0.$INCREMENT
	NETMASK=255.255.255.0
EOF
	echo "192.168.0.0/24 via 172.18.0.254 dev bond0.3" > /etc/sysconfig/network-scripts/route-bond0.3
fi
INCREMENT=`echo $NEWHOSTNAME | egrep -o '^atcdc-vh[0-9]+' | awk -F- '{print $2}' | awk -F. '{print $1}' | egrep -o '[0-9]+'`
if [ ${#INCREMENT} -ne 0 ]; then
  BACKBONE=10.0.192.$INCREMENT
  cat >> /etc/sysconfig/network-scripts/ifcfg-bond0.2 <<-EOF
  IPADDR=$BACKBONE
  NETMASK=255.255.192.0
EOF
	for i in {1..250}; do echo -e "10.0.192.$i\tatcdc-vh$i"; done >> /etc/hosts
	cat >> /etc/sysconfig/network-scripts/ifcfg-bond0.3 <<-EOF
	DEVICE=bond0.3
	ONBOOT=yes
	VLAN=yes
	MTU=1500
	IPV6INIT=no
	IPV6PREFIX=64
	IPV6_AUTOCONF=no
	BOOTPROTO=static
	IPADDR=10.134.16.$INCREMENT
	NETMASK=255.255.255.0
EOF
	echo "192.168.0.0/24 via 10.134.16.254 dev bond0.3" > /etc/sysconfig/network-scripts/route-bond0.3
fi
INCREMENT=`echo $NEWHOSTNAME | egrep -o '^sh-vh[0-9]+' | awk -F- '{print $2}' | awk -F. '{print $1}' | egrep -o '[0-9]+'`
if [ ${#INCREMENT} -ne 0 ]; then
  BACKBONE=10.1.128.$INCREMENT
  cat >> /etc/sysconfig/network-scripts/ifcfg-bond0.2 <<-EOF
  IPADDR=$BACKBONE
  NETMASK=255.255.192.0
EOF
	for i in {1..250}; do echo -e "10.1.128.$i\tsh-vh$i"; done >> /etc/hosts
	cat >> /etc/sysconfig/network-scripts/ifcfg-bond0.3 <<-EOF
	DEVICE=bond0.3
	ONBOOT=yes
	VLAN=yes
	MTU=1500
	IPV6INIT=no
	IPV6PREFIX=64
	IPV6_AUTOCONF=no
	BOOTPROTO=static
	IPADDR=10.134.72.$INCREMENT
	NETMASK=255.255.255.0
EOF
	echo "192.168.0.0/24 via 10.134.72.254 dev bond0.3" > /etc/sysconfig/network-scripts/route-bond0.3
fi
INCREMENT=`echo $NEWHOSTNAME | egrep -o '^fas-vh[0-9]+' | awk -F- '{print $2}' | awk -F. '{print $1}' | egrep -o '[0-9]+'`
if [ ${#INCREMENT} -ne 0 ]; then
  BACKBONE=10.1.0.$INCREMENT
  cat >> /etc/sysconfig/network-scripts/ifcfg-bond0.2 <<-EOF
  IPADDR=$BACKBONE
  NETMASK=255.255.192.0
EOF
	for i in {1..250}; do echo -e "10.1.0.$i\tfas-vh$i"; done >> /etc/hosts
	cat >> /etc/sysconfig/network-scripts/ifcfg-bond0.3 <<-EOF
	DEVICE=bond0.3
	ONBOOT=yes
	VLAN=yes
	MTU=1500
	IPV6INIT=no
	IPV6PREFIX=64
	IPV6_AUTOCONF=no
	BOOTPROTO=static
	IPADDR=10.134.32.$INCREMENT
	NETMASK=255.255.255.0
EOF
	echo "192.168.0.0/24 via 10.134.32.254 dev bond0.3" > /etc/sysconfig/network-scripts/route-bond0.3
fi
INCREMENT=`echo $NEWHOSTNAME | egrep -o '^stc-vh[0-9]+' | awk -F- '{print $2}' | awk -F. '{print $1}' | egrep -o '[0-9]+'`
if [ ${#INCREMENT} -ne 0 ]; then
  BACKBONE=10.1.64.$INCREMENT
  cat >> /etc/sysconfig/network-scripts/ifcfg-bond0.2 <<-EOF
  IPADDR=$BACKBONE
  NETMASK=255.255.192.0
EOF
	for i in {1..250}; do echo -e "10.1.0.$i\tfas-vh$i"; done >> /etc/hosts
	cat >> /etc/sysconfig/network-scripts/ifcfg-bond0.3 <<-EOF
	DEVICE=bond0.3
	ONBOOT=yes
	VLAN=yes
	MTU=1500
	IPV6INIT=no
	IPV6PREFIX=64
	IPV6_AUTOCONF=no
	BOOTPROTO=static
	IPADDR=10.134.48.$INCREMENT
	NETMASK=255.255.255.0
EOF
	echo "192.168.0.0/24 via 10.134.32.254 dev bond0.3" > /etc/sysconfig/network-scripts/route-bond0.3
fi

[ "$UNATTENDED" = "" ] &&  dialog  --msgbox "zapojte modry a bily kabel, pak zmacknete OK." 0 0
/etc/init.d/network start
sleep 3
ping6 -c 1 ns1.hosting90.cz >/dev/null
 ;;
1)
  echo "You have pressed Cancel" 
  exit
 ;;
255)
  echo "Box closed"  ;;
esac
}

create_filter() {
	cat > /tmp/nwfilter.xml << "EOF"
<filter name='drop-smtp' chain='root' priority='-700'>
  <uuid>a6395c96-9ec6-49b2-851f-5491edaa89d4</uuid>
  <rule action='drop' direction='out' priority='-1000'>
    <ip protocol='tcp' dstportstart='25'/>
  </rule>
  <rule action='drop' direction='out' priority='-1000'>
    <ip protocol='tcp' dstportstart='465'/>
  </rule>
  <rule action='drop' direction='out' priority='-1000'>
    <ip protocol='tcp' dstportstart='587'/>
  </rule>
  <rule action='drop' direction='out' priority='-1000'>
    <ipv6 protocol='tcp' dstportstart='25'/>
  </rule>
  <rule action='drop' direction='out' priority='-1000'>
    <ipv6 protocol='tcp' dstportstart='465'/>
  </rule>
  <rule action='drop' direction='out' priority='-1000'>
    <ipv6 protocol='tcp' dstportstart='587'/>
  </rule>
</filter>
EOF
	virsh nwfilter-define /tmp/nwfilter.xml

	cat > /tmp/myfilter.xml <<EOF
<filter name='allow-ipv6' chain='ipv6' priority='-600'>
  <rule action='accept' direction='inout' priority='500'/>
</filter>
EOF
	virsh nwfilter-define /tmp/myfilter.xml

	cat > /tmp/nwfilter.xml << "EOF"
<filter name='no-ip-spoofing-subnet' chain='ipv4-ip' priority='-710'>
  <rule action='return' direction='out' priority='100'>
    <ip srcipaddr='0.0.0.0' protocol='udp'/>
  </rule>
  <rule action='return' direction='out' priority='500'>
    <ip srcipaddr='$IP'/>
  </rule>
  <rule action='return' direction='out' priority='500'>
    <ip srcipaddr='$IPV4_SUBNET[@1]' srcipmask='$IPV4_NETMASK[@1]'/>
  </rule>
  <rule action='drop' direction='out' priority='1000'/>
</filter>
EOF
	virsh nwfilter-define /tmp/nwfilter.xml

	cat > /tmp/nwfilter.xml << "EOF"
<filter name='allow-incoming-ipv6' chain='ipv6' priority='-700'>
  <rule action='accept' direction='in' priority='500'/>
</filter>
EOF
	virsh nwfilter-define /tmp/nwfilter.xml

	cat > /tmp/nwfilter.xml << "EOF"
<filter name='ipv6-no-ip-spoofing' chain='ipv6' priority='-710'>
  <rule action='accept' direction='out' priority='100'>
    <ipv6 srcipaddr='ff00::' srcipmask='12' protocol='icmpv6'/>
  </rule>
  <rule action='accept' direction='out' priority='100'>
    <ipv6 srcipaddr='fe80::' srcipmask='64'/>
  </rule>
  <rule action='accept' direction='out' priority='500'>
    <ipv6 srcipaddr='$IPV6'/>
  </rule>
  <rule action='accept' direction='out' priority='500'>
    <ipv6 srcipaddr='$IPV6_SUBNET[@1]' srcipmask='$IPV6_NETMASK[@1]'/>
  </rule>
  <rule action='drop' direction='out' priority='1000'/>
</filter>
EOF
	virsh nwfilter-define /tmp/nwfilter.xml
	
	cat > /tmp/myfilter.xml <<EOF
<filter name='drop-invalid-udp' chain='ipv4' priority='100'>
	<rule action='accept' direction='inout' priority='200'>
		<ip protocol='udp' match='yes' dstportstart='1' dstportend='65535' srcportstart='1' srcportend='65535'/>
		</rule>
		<rule action='drop' direction='inout' priority='300'>
			<ip protocol='udp' match='yes'/>
		</rule>
</filter>
EOF
	virsh nwfilter-define /tmp/myfilter.xml

# IPV6
	cat > /tmp/myfilter.xml <<EOF
<filter name='no-dhcpv6-server' chain='ipv6' priority='-680'>
  <rule action='drop' direction='out' priority='100'>
    <ipv6 protocol='udp' dstportstart='546'/>
  </rule>
</filter>
EOF
	virsh nwfilter-define /tmp/myfilter.xml

	cat > /tmp/myfilter.xml <<EOF
<filter name='no-ipv6-router-advertisement' chain='root' priority='-690'>
  <rule action='drop' direction='out' priority='600'>
    <icmpv6 type='134'/>
  </rule>
  <rule action='drop' direction='out' priority='600'>
    <icmpv6 type='153'/>
  </rule>
</filter>
EOF
	virsh nwfilter-define /tmp/myfilter.xml

	cat > /tmp/nwfilter.xml << "EOF"
<filter name='filter-vps-default' chain='root'>
  <filterref filter='no-mac-spoofing'/>
  <filterref filter='no-ip-spoofing-subnet'/>
  <rule action='accept' direction='out' priority='-650'>
    <mac protocolid='ipv4'/>
  </rule>
  <filterref filter='allow-incoming-ipv4'/>
  <filterref filter='allow-dhcp'/>
  <filterref filter='ipv6-no-ip-spoofing'/>
  <filterref filter='drop-invalid-udp'/>
  <filterref filter='no-dhcpv6-server'/>
  <filterref filter='no-ipv6-router-advertisement'/>
  <filterref filter='allow-incoming-ipv6'/>
  <filterref filter='no-arp-spoofing'/>
  <rule action='accept' direction='inout' priority='-500'>
    <mac protocolid='arp'/>
  </rule>
  <filterref filter='no-other-l2-traffic'/>
  <filterref filter='qemu-announce-self'/>
</filter>
EOF
	virsh nwfilter-define /tmp/nwfilter.xml
	cat > /tmp/myfilter.xml <<EOF
<filter name='clean-traffic-antispam' chain='root'>
	<filterref filter='no-mac-spoofing'/>
	<rule action='accept' direction='out' priority='-650'>
		<mac protocolid='ipv4'/>
	</rule>
	<filterref filter='allow-dhcp'/>
	<filterref filter='allow-ipv4'/>
	<filterref filter='allow-ipv6'/>
	<filterref filter='allow-incoming-ipv4'/>
	<filterref filter='no-arp-spoofing'/>
	<rule action='accept' direction='inout' priority='-500'>
		<mac protocolid='arp'/>
	</rule>
	<filterref filter='no-other-l2-traffic'/>
	<filterref filter='qemu-announce-self'/>
</filter>
EOF
	virsh nwfilter-define /tmp/myfilter.xml
	cat > /tmp/myfilter.xml <<EOF
<filter name='open-ip-policy' chain='root'>
	<filterref filter='no-mac-spoofing'/>
	<rule action='accept' direction='out' priority='-650'>
		<mac protocolid='ipv4'/>
	</rule>
	<filterref filter='allow-arp'/>
	<filterref filter='allow-dhcp'/>
	<filterref filter='allow-ipv4'/>
	<filterref filter='allow-ipv6'/>
	<filterref filter='no-other-l2-traffic'/>
	<filterref filter='qemu-announce-self'/>
</filter>
EOF
	virsh nwfilter-define /tmp/myfilter.xml
# blokovani spameru. k vychozimu VPS filtru je doplneno zahazovani provozu na SMTP
	cat > /tmp/nwfilter.xml << "EOF"
<filter name='filter-vps-smtp_block' chain='root'>
  <filterref filter='drop-smtp'/>
  <filterref filter='filter-vps-default'/>
</filter>
EOF
	virsh nwfilter-define /tmp/nwfilter.xml
	rm -f /tmp/myfilter.xml
}

setup_scripts() {
if [ $HOUSING_NAME = coh ]; then
  export MONITORING='coh-sys1.hosting90.cz'
	echo '10.0.127.251:/mnt/data/install /mnt/install       nfs     _netdev,rw,async,auto,context="system_u:object_r:virt_content_t:s0"      0 0' >>  /etc/fstab
elif [ $HOUSING_NAME = slovanet ]; then
  export MONITORING='slo-sys1.hosting90.cz'
	echo '10.0.191.1:/mnt/data/install /mnt/install       nfs     _netdev,rw,async,auto,context="system_u:object_r:virt_content_t:s0"      0 0' >>  /etc/fstab
elif [ $HOUSING_NAME = atcdc ]; then
  export MONITORING='atcdc-sys1.hosting90.cz'
	echo '10.0.255.1:/mnt/data/install /mnt/install       nfs     _netdev,rw,async,auto,context="system_u:object_r:virt_content_t:s0"      0 0' >>  /etc/fstab
elif [ $HOUSING_NAME = sh ]; then
  export MONITORING='sh-varch1.hosting90.cz'
	echo '10.1.191.254:/mnt/data/install /mnt/install       nfs     _netdev,rw,async,auto,context="system_u:object_r:virt_content_t:s0"      0 0' >>  /etc/fstab
elif [ $HOUSING_NAME = fas ]; then
  export MONITORING='fas-sys1.hosting90.cz'
	echo '10.1.63.1:/mnt/data/install /mnt/install       nfs     _netdev,rw,async,auto,context="system_u:object_r:virt_content_t:s0"      0 0' >>  /etc/fstab
elif [ $HOUSING_NAME = stc ]; then
  export MONITORING='stc-sys1.hosting90.cz'
	echo '10.1.127.1:/mnt/data/install /mnt/install       nfs     _netdev,rw,async,auto,context="system_u:object_r:virt_content_t:s0"      0 0' >>  /etc/fstab
else
  export MONITORING='naemon.hosting90.cz'
	echo '10.0.1.2:/mnt/data/install /mnt/install       nfs     _netdev,rw,async,auto,context="system_u:object_r:virt_content_t:s0"      0 0' >>  /etc/fstab
fi
echo "* * * * * root /root/server/virtual/cleaner/virt-clean.py" > /etc/crontab
echo "1 0 * * * root /root/server/tools/virtual-backupall.sh" >> /etc/crontab
echo '* * * * * root PATH=/sbin:/usr/sbin:$PATH sh /root/server/tools/vh_checkpoweroff.sh' >> /etc/crontab
echo "*/5 * * * * root ! [ -e /dev/HostVG/temp_cleaner ] && ( if [ \`grep idle /sys/block/md*/md/sync_action | wc -l\` -eq \`ls -1 /sys/block/md*/md/sync_action | wc -l\` ]; then if [ -e /root/.keepred ]; then rm -f /root/.keepred; curl 'https://administrace.hosting90.cz/cron/server_state_update?server_name=`hostname`&maintenance=1&empty=0&comment=' >/dev/null 2>/dev/null; else curl 'https://administrace.hosting90.cz/cron/server_state_update?server_name=`hostname`&maintenance=0&empty=0&comment=' >/dev/null 2>/dev/null; fi ; sed -i '/temp_cleaner/d' /etc/crontab; curl 'http://$MONITORING/cgi-bin/naemon_notification.py?host=`hostname -s`&setto=on' > /dev/null 2>/dev/null; rm -f /root/.autoreinstall; else curl 'https://administrace.hosting90.cz/cron/server_state_update?server_name=`hostname`&comment=3\%2F3+cisteni+disku+a+resync+raidu+`date +"%Y-%m-%d+%H:%M"`' >/dev/null 2>/dev/null; fi) " >> /etc/crontab
mkdir /etc/libvirt_watchdog
mkdir -p /usr/virt/conf
echo '* * * * * root sleep $(($RANDOM \% 50)); /root/server/virtual/memcache-status.py' > /etc/cron.d/memcache-status
cp -a /root/server/syscmdcli /etc/init.d/syscmdcli
chkconfig syscmdcli on
sed -i 's/^/#/' /usr/share/dbus-1/system-services/org.freedesktop.ConsoleKit.service


cat >> /etc/systemd/system/backup-manager.service <<EOF
[Unit]
Description=Zalohovaci daemon
After=local-fs.target network-online.target
Requires=local-fs.target network-online.target

[Service]
Type=forking
User=root
ExecStart=/root/server/virtual/backup/manager.py --start
ExecStop=/root/server/virtual/backup/manager.py --stop
ExecReload=/root/server/virtual/backup/manager.py --restart
PIDFile=/var/run/backupd-manager.pid
Restart=always

[Install]
WantedBy=multi-user.target
EOF
systemctl enable backup-manager.service
systemctl start backup-manager.service

cat > /etc/rc.local <<"EOF"
#!/bin/bash

#Enable RPS,XPS
echo 32768 > /proc/sys/net/core/rps_sock_flow_entries

#MD raid params
for md in /sys/block/md*/md/max_read_errors; do echo 5 > $md; done
#Set error recovery time to 2s
for i in `egrep -o sd[a-z]{1}$ /proc/partitions`; do smartctl -l scterc,20,20 /dev/$i; done

#KSM
echo 10000 > /sys/kernel/mm/ksm/pages_to_scan
echo 20 > /sys/kernel/mm/ksm/sleep_millisecs
echo 1 > /sys/kernel/mm/ksm/run
touch /var/lock/subsys/local
auditctl -e 0

REBOOTETH=0
for iface in `cat /proc/net/dev | tail -n+3 | grep -v -e vps -e vbr -e bond -e "lo:" -e vnet |awk -F: '{print $1}'`; do
	echo ff > /sys/class/net/$iface/queues/rx-0/rps_cpus
	echo ff > /sys/class/net/$iface/queues/tx-0/xps_cpus
	echo 16384 > /sys/class/net/$iface/queues/rx-0/rps_flow_cnt
	#FIX i82574
	/root/server/tools/fixeep-82574_83.sh $iface && REBOOTETH=1
done
if [ $REBOOTETH -eq 1 ]; then
        /sbin/reboot
fi
EOF
if cat /etc/redhat-release | grep " 7"; then
	cat >> /etc/rc.local <<"EOF"
# iptables
iptables-restore < /etc/sysconfig/iptables
ip6tables-restore < /etc/sysconfig/ip6tables

# set hard limit on memory for libvirt guests
[ ! -d /sys/fs/cgroup/memory/machine.slice ] && mkdir /sys/fs/cgroup/memory/machine.slice
echo $((`cat /proc/meminfo | grep MemTotal | awk '{print $2}'`*1024*95/100)) > /sys/fs/cgroup/memory/machine.slice/memory.limit_in_bytes
sh /root/server/tools/disable-aspm.sh

SNAME=`hostname -s`
if [ "${SNAME:0:5}" = "hc-vh" ]; then
	# wait for network
	TT=$((`date +%s`+30)) # timeout
	while ! ping -c 1 ns1.hosting90.cz >/dev/null 2>&1; do
		if [ `date +%s` -gt $TT ]; then
			break;
		fi
		sleep 1;
	done
	curl "http://naemon.hosting90.cz/cgi-bin/naemon_notification.py?host=`hostname -s`&setto=on"
	curl "http://centrumv3.hosting90.cz/cron/server_state_update?server_name=`hostname`&power_down=0"
fi
EOF
fi
chmod +x /etc/rc.d/rc.local

cat > /etc/libvirt/libvirtd.conf <<EOF
unix_sock_group = "libvirt"
mdns_adv = 0
listen_tcp = 0
listen_tls = 0
EOF

DISKY=$(egrep -o sd[a-z]{1}$ /proc/partitions | sort | sed 's/sd//g' | xargs echo -n | sed 's/ //g')
ln -s /root/server/virtual/collectd_vcpu_quota.py /usr/lib64/collectd/collectd_vcpu_quota.py
cat > /etc/collectd.conf <<EOF
FQDNLookup   true

LoadPlugin logfile
LoadPlugin network
LoadPlugin libvirt

LoadPlugin cpu
LoadPlugin load
LoadPlugin memory
LoadPlugin disk
LoadPlugin contextswitch
LoadPlugin python

<Plugin logfile>
	LogLevel err
	File "/var/log/collectd.log"
	Timestamp true
</Plugin>

<Plugin "virt">
	Connection "qemu:///system"
	RefreshInterval 60
	HostnameFormat "uuid"
	PluginInstanceFormat "name"
	Domain "/^guestfs[-0-9a-zA-Z]*$/"
	IgnoreSelected true
</Plugin>
<Plugin network>
        Server "$COLLECTD_SERVER" "25826"
</Plugin>

<Plugin "disk">
  Disk "/^sd[$DISKY]$/"
  IgnoreSelected false
</Plugin>

<Plugin python>
ModulePath "/usr/lib64/collectd"
    Import "collectd_vcpu_quota"
    <Module collectd_vcpu_quota>
        Interval 2
        Count 2
        Verbose false
    </Module>
</Plugin>
EOF
chkconfig collectd on

# smartd
for i in `egrep -o sd[a-z]{1}$ /proc/partitions | sort`; do
cat >> /etc/smartd.conf <<EOF
/dev/$i -l error \
     -m admin@hosting90.cz \
           -l selftest \
           -t \      # Attributes not tracked:
           -I 194 \  # temperature
           -I 231 \  # also temperature
           -I 9      # power-on hours
EOF
done

if [ $HOUSING_NAME = coh ]; then
 BACKUP_SERVER=10.0.127.251
elif [ $HOUSING_NAME = slovanet ]; then
 BACKUP_SERVER=10.0.191.1
elif [ $HOUSING_NAME = atcdc ]; then
 BACKUP_SERVER=10.0.255.1
elif [ $HOUSING_NAME = fas ]; then
 BACKUP_SERVER=10.1.63.1
elif [ $HOUSING_NAME = stc ]; then
 ADDITIONAL_RULES='-A INPUT -i bond0.3 -j ACCEPT'
 BACKUP_SERVER=10.1.127.1
elif [ $HOUSING_NAME = sh ]; then
 BACKUP_SERVER=10.1.191.254
else
 BACKUP_SERVER=10.0.1.1
fi
#BACKUP_SERVER=$(dialog --title --stdout "backup" --inputbox "zadejte server, na ktery budou ukladany zalohy:" 8 50 "$BACKUP_SERVER") 
echo $BACKUP_SERVER > /root/.archiv-name.conf
chmod +x /root/server/virtual/backup/insert.py
#sed -i "s/\[virtualy;localhost\]/[virtualy;`hostname -s`]/" /etc/munin/munin.conf

}

setup_iptables() {
	service iptables stop
	service ip6tables stop
	iptables-restore <<EOF
*nat
:PREROUTING ACCEPT [2:281]
:INPUT ACCEPT [1:52]
:OUTPUT ACCEPT [0:0]
:POSTROUTING ACCEPT [0:0]
-A PREROUTING -p tcp -m tcp --dport 5900 --tcp-flags FIN,SYN,RST,ACK SYN -m connlimit --connlimit-above 5 --connlimit-mask 32 --connlimit-saddr -j LOG
COMMIT
*filter
:INPUT DROP [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
:VIP - [0:0]
:VNC - [0:0]
-A INPUT -p icmp -j ACCEPT 
-A INPUT -i lo -j ACCEPT
-A INPUT -i bond0.2 -j ACCEPT
$ADDITIONAL_RULES
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A INPUT -j VIP 
-A INPUT -j VNC
-A VIP -m iprange --src-range 130.193.8.64-130.193.8.255 -m  comment --comment "rozsah vh*, ns1, munin, VPN" -j ACCEPT
-A VIP -s 130.193.9.128/25 -m comment --comment "hc-vh, od vh124" -j ACCEPT
-A VIP -s 86.49.171.64/27 -m  comment --comment "faster vh" -j ACCEPT
-A VIP -s 217.145.205.64/26 -m  comment --comment "slovanet vh" -j ACCEPT
-A VIP -s 89.187.138.128/25 -m  comment --comment "coolhousing vh" -j ACCEPT
-A VIP -s 130.185.183.224/24 -m  comment --comment "atcdc vh" -j ACCEPT
-A VIP -s 10.134.16.1/24 -m comment --comment "atcdc vh VPN" -j ACCEPT
-A VIP -s 82.208.43.145/32 -m comment --comment "office.hosting90.cz" -j ACCEPT 
-A VIP -s 130.193.14.216/29 -m comment --comment "office" -j ACCEPT 
-A VIP -s 192.168.0.0/24 -m comment --comment "office - instalace v kanclu" -j ACCEPT
-A VIP -s 87.236.194.196 -m comment --comment "ns2" -j ACCEPT 
-A VIP -s 130.193.9.46 -m comment --comment "dnscache2" -j ACCEPT 
-A VIP -s 130.193.9.36 -m comment --comment "dnscache1" -j ACCEPT 
-A VIP -s 89.187.128.37 -m comment --comment "kulna munin" -j ACCEPT
-A VIP -s 37.46.82.109 -m comment --comment "ansible" -j ACCEPT
COMMIT
EOF

	ip6tables-restore <<EOF
*filter
:INPUT DROP [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
:VIP - [0:0]
-A INPUT -p icmpv6 -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -i bond0.2 -j ACCEPT
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -j VIP
#CASABLANCA
-A VIP -s 2001:1528:124::/48 -j ACCEPT
#hc-vh
-A VIP -s 2a03:b780:0:200::/64 -j ACCEPT
#coh-vh
-A VIP -s 2a01:5f0:c001:122:1::/64 -j ACCEPT
#h90-ns1
-A VIP -s 2a03:b780::/64 -j ACCEPT
#svn
-A VIP -s 2a03:b780:1:1::/64 -j ACCEPT
#ns2
-A VIP -s 2001:1528:1:a700::1:1 -j ACCEPT
COMMIT
EOF
#	service iptables save
#	service ip6tables save
	iptables-save > /etc/sysconfig/iptables
	ip6tables-save > /etc/sysconfig/ip6tables
}

setup_nrpe() {
if [ "$UNATTENDED" = "" ]; then
	FANN=$((ipmitool sensor 2>/dev/null || sensors w83795adg-i2c-0-2e 2>/dev/null) | egrep -i "fan[ ]?[A-Z0-9]+" | egrep -io "(:[ ]*([0-9]+) RPM)|(\|[ ]*([0-9.]+)[ ]*\| RPM)" | wc -l)
  FANN=$(dialog --title --stdout "fann" --inputbox "Zadejte pocet vetracku:" 8 30 "$FANN")
  if [ $? -eq 1 ]; then
    echo "Cancel pressed."; exit
  fi
fi

usermod -a -G libvirt nrpe
usermod -a -G wireshark nrpe
cat > /etc/libvirt/libvirtd.conf << EOF
unix_sock_group = "libvirt"
EOF

mkdir /var/log/munin/
chkconfig munin-node on

cat > /etc/munin/munin-node.conf << EOF
log_level 4
log_file /var/log/munin/munin-node.log
pid_file /var/run/munin/munin-node.pid

background 1
setsid 1

user root
group root

# Regexps for files to ignore

ignore_file ~$
#ignore_file [#~]$  # FIX doesn't work. '#' starts a comment
ignore_file DEADJOE$
ignore_file \.bak$
ignore_file %$
ignore_file \.dpkg-(tmp|new|old|dist)$
ignore_file \.rpm(save|new)$
ignore_file \.pod$

allow ^127\.0\.0\.1$
allow ^130\.193\.8\.93$

host *
port 4949
EOF

cat > /etc/nagios/syn_flood.def << EOF
@searches = (
  {
    tag => 'system msg',
    logfile => '/var/log/messages',
    rotation => 'CENTOS',
    options => 'sticky=60',
    criticalpatterns => [
        'oom_kill_process',
        'Possible SYN flooding on port'
    ],
  },
  );
EOF
mkdir /var/tmp/check_logfiles
chown -R nrpe:nrpe /var/tmp/check_logfiles

cat > /etc/nagios/sensors.ini << EOF
[fan]
number = $FANN
warning_limit = 1000
critical_limit = 600

[temp]
warning_limit = 73
critical_limit = 81
EOF

cat > /etc/nagios/nrpe.cfg << EOF
log_facility=daemon
pid_file=/var/run/nrpe/nrpe.pid
server_port=5666
nrpe_user=nrpe
nrpe_group=nrpe
debug=0
command_timeout=50
connection_timeout=60
allowed_hosts=130.193.8.92,2a03:b780::1:6,10.0.0.0/8,130.185.183.254,89.187.138.254
dont_blame_nrpe=1
command[check_libvirt]=/root/server/virtual/nagios-plugins/check_libvirt.py
command[check_sensors]=/root/server/virtual/nagios-plugins/check_sensors.py -f /etc/nagios/sensors.ini
command[check_virtual_backup]=/root/server/virtual/nagios-plugins/check_backup.py -w 36 -c 48
command[check_load]=/usr/lib64/nagios/plugins/check_load -w 28,28,28 -c 60,60,60
command[check_mcelog]=/root/server/virtual/nagios-plugins/check_mcelog.py -s 300
command[check_synflood]=/usr/lib64/nagios/plugins/check_logfiles -f /etc/nagios/syn_flood.def
command[record_synflood]=/root/server/virtual/nagios-plugins/record_synflood.py \$ARG1$ \$ARG2$ \$ARG3$
command[check_thinpool_usage]=/root/server/virtual/nagios-plugins/check_thinpool_usage.py
command[check_syscmdcli_procs]=/usr/lib64/nagios/plugins/check_procs --ereg-argument-array='new_command_sock.py|new_command_rpc.py' -c 3:4
command[check_collectd_log]=/root/server/virtual/nagios-plugins/check_collectd_log.py -l /var/log/collectd.log -m 15 -w 1 -c 8
command[check_mounts]=/root/server/virtual/nagios-plugins/check_mounts.py
command[remount_mounts]=/root/server/virtual/nagios-plugins/check_mounts.py \$ARG1$ \$ARG2$ \$ARG3$
EOF
chmod 0644 /var/log/messages
usermod -a -G systemd-journal nrpe

cat > /etc/sysconfig/lm_sensors << EOF
HWMON_MODULES="coretemp w83795"
MODULE_0=coretemp
MODULE_1=w83795
EOF

chmod 751 /root
chmod 755 /etc/libvirt_watchdog
mkdir -p /usr/lib/nagios/plugins
if ! cat /etc/redhat-release | grep " 7" > /dev/null; then
	echo 'override w83795 * weak-updates/w83795' > /etc/depmod.d/kmod-w83795.conf
	mkdir -p /lib/modules/`uname -r`/extra/w83795
	cp /root/server/tools/lm_sensors/w83795/w83795.ko /lib/modules/`uname -r`/extra/w83795
	depmod -a
	#semodule -i /root/nrpe_local.pp
	chkconfig lm_sensors on
fi
chkconfig nrpe on
}

setup_ssh() {
mkdir /root/.ssh
cat > /root/.ssh/authorized_keys << EOF
ssh-rsa [payload removed: 372 characters] spinka@hosting90.cz
ssh-rsa [payload removed: 372 characters] hilgard@hosting90.cz
ssh-rsa [payload removed: 372 characters] jakub.petr@hosting90.cz
ssh-rsa [payload removed: 372 characters] jiri.lunacek@hosting90.cz
ssh-rsa [payload removed: 372 characters] andrei.toupinets@hosting90.cz
ssh-rsa [payload removed: 372 characters] martin.gula@hosting90.cz
ssh-rsa [payload removed: 372 characters] marek.chrastina@hosting90.cz
ssh-rsa [payload removed: 372 characters] stanislaw.gackowski@hosting90.cz
ssh-rsa [payload removed: 372 characters] jan.kucera@hosting90.cz

ssh-rsa [payload removed: 372 characters] root@vh-test
ssh-rsa [payload removed: 372 characters] root@ansible-manager
EOF

cat > /root/.ssh/authorized_keys2 << "EOF"
command="if nc -q 2>&1 | grep \"requires an argument\" >/dev/null 2>&1; then ARG=-q0;else ARG=;fi;nc $ARG -U /var/run/libvirt/libvirt-sock" ssh-rsa [payload removed: 372 characters] apache@adm.hosting90.cz
EOF

cat > /root/.ssh/id_rsa << EOF
-----BEGIN RSA PRIVATE KEY-----
[payload removed: 1588 characters in 25 lines]
-----END RSA PRIVATE KEY-----
EOF

cat > /root/.ssh/id_rsa.pub << EOF
ssh-rsa [payload removed: 372 characters] root@vh-test
EOF
chmod 0600 /root/.ssh/id_rsa
chmod 0644 /root/.ssh/id_rsa.pub
chmod 700 /root/.ssh/authorized_keys
restorecon -R /root/.ssh
}

setup_fail2ban() {
cat > /etc/fail2ban/jail.d/custom.local << EOF
[vnc-bruteforce]
enabled = true  
filter  = vnc-bruteforce
action  = iptables[name=vnc-bruteforce]  
logpath = /var/log/messages  
maxretry = 3
banaction = iptables-allports
EOF

cat > /etc/fail2ban/filter.d/vnc-bruteforce.conf <<EOF
[Definition]
failregex = ^.*IN=vbr100 .*SRC=<HOST> .* PROTO=TCP .* DPT=5900 .*
ignoreregex =
EOF
chkconfig fail2ban on
}

setup_libvirt_hooks() {
mkdir -p /etc/libvirt/hooks
chmod +x /root/server/virtual/hooks/*
ln -s /root/server/virtual/hooks/* /etc/libvirt/hooks/
}

setup_disks() {
# thinpool a cleaner
MD_SSD_ARRAY=()
MD_HDD_ARRAY=()
MD_HDD_FREE_SIZE=0
MD_SSD_FREE_SIZE=0
readarray -t MD_ARRAY <<< "$(cat /proc/mdstat | grep -v md0 | egrep -o md[0-9])"
for md in ${MD_ARRAY[@]}; do
  readarray -t DISKY <<< "$(cat /proc/mdstat | grep $md | egrep -o sd[a-z]{1})"
  if [ `cat /sys/block/${DISKY[0]}/queue/rotational /sys/block/${DISKY[1]}/queue/rotational | grep 0 | wc -l` -eq 0 ]; then
    MD_HDD_ARRAY+=($md)
    MD_HDD_FREE_SIZE=$(($MD_HDD_FREE_SIZE+`pvs --units B --noheadings -o pv_free /dev/$md | sed 's/ //g;s/B//'`))
  elif [ `cat /sys/block/${DISKY[0]}/queue/rotational /sys/block/${DISKY[1]}/queue/rotational | grep 1 | wc -l` -eq 0 ]; then
    MD_SSD_ARRAY+=($md)
    MD_SSD_FREE_SIZE=$(($MD_SSD_FREE_SIZE+`pvs --units B --noheadings -o pv_free /dev/$md | sed 's/ //g;s/B//'`))
  fi
done
if [ ${#MD_SSD_ARRAY[@]} -eq 1 ]; then
  printf -v MD_SSD_LIST "/dev/%s " ${MD_SSD_ARRAY[@]}
  lvcreate -T -n thinpool -c 128k -Z n -L$((($MD_SSD_FREE_SIZE-2**(28+${#MD_SSD_ARRAY[@]}))/512*512))B HostVG $MD_SSD_LIST
fi
if [ ${#MD_SSD_ARRAY[@]} -gt 1 ]; then
  printf -v MD_SSD_LIST "/dev/%s " ${MD_SSD_ARRAY[@]}
  lvcreate -T -n thinpool -i ${#MD_SSD_ARRAY[@]} -I 128k -c 128k -Z n -L$((($MD_SSD_FREE_SIZE-2**(28+${#MD_SSD_ARRAY[@]}))/512*512))B HostVG $MD_SSD_LIST
fi
if [ ${#MD_HDD_ARRAY[@]} -eq 1 ]; then
  printf -v MD_HDD_LIST "/dev/%s " ${MD_HDD_ARRAY[@]}
  lvcreate -n temp_cleaner -L${MD_HDD_FREE_SIZE}B HostVG $MD_HDD_LIST
  touch /root/server/virtual/cleaner/queue/temp_cleaner
fi
if [ ${#MD_HDD_ARRAY[@]} -gt 1 ]; then
  printf -v MD_HDD_LIST "/dev/%s " ${MD_HDD_ARRAY[@]}
  lvcreate -n temp_cleaner -i ${#MD_HDD_ARRAY[@]} -I 1m -L${MD_HDD_FREE_SIZE}B HostVG $MD_HDD_LIST
  touch /root/server/virtual/cleaner/queue/temp_cleaner
fi
sed -i '/dev.raid.speed_limit_max = 1024/d' /etc/sysctl.conf
curl --connect-timeout 5 "https://administrace.hosting90.cz/cron/server_state_update?server_name=`hostname`&comment=3%2F3+cisteni+disku+a+resync+raidu+`date +"%Y-%m-%d+%H:%M"`"
}

setup_network
setup_scripts
create_filter
setup_iptables
setup_nrpe
setup_ssh
setup_libvirt_hooks
setup_fail2ban

if [ -f /root/.has_discard_capability ]; then
	ln -s /root/server/virtual/munin-plugins/plugins/disk_tbw /etc/munin/plugins/
	ln -s /root/server/virtual/munin-plugins/conf.d/disk_tbw /etc/munin/plugin-conf.d/
fi

setup_disks

# self-remove
if [ "$UNATTENDED" = "" ]; then
  dialog --yesno " ==== KONEC ==== \n\n Smazat setup.sh?\n\n(DOPORUCENO)" 0 0
  if [ $? -eq 0 ]; then
    /bin/rm /root/setup.sh
  fi
else
  /bin/rm /root/setup.sh
fi

if [ "$UNATTENDED" = "" ]; then
echo -e "\nDONE\nReboot your server..."
else
reboot
fi

