#!/bin/sh
##############################################################################
#
# Copyright (c) 2010 Vifib SARL and Contributors. All Rights Reserved.
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsibility of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# guarantees and support are strongly advised to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
##############################################################################

systemctl stop slapos-node.service
systemctl disable slapos-node.service

# clean the system
for service in rpcbind network-remotefs postfix ; do
  chkconfig --del $service
  /etc/init.d/$service stop
done

IPV6CHECK=ipv6.google.com
IPV4CHECK=google.com
IPV6WAITTIME=5
SLAPVPN="ipv6_interface = tapVPN"

SLAPOS_CONFIGURATION='%(slapos_configuration)s'

# Test ipv4/ipv6 connectivity and if not working use openvpn 
# and wait for it to be ready
/etc/init.d/openvpn stop

ping -c 2 $IPV4CHECK
while [ $? != 0 ]; do
    sleep 5
    ping -c 2 $IPV4CHECK
done

echo """Ipv4 connection ok"""

# Wait for native ipv6 connection to be ready 
i=0
ping6 -c 2 $IPV6CHECK
while [[ $? != 0 ]] && [[ $i < $IPV6WAITTIME ]]
do
    let i++
    sleep 1
    ping6 -c 2 $IPV6CHECK
done

if [ $? != 0 ] || [ -f $SLAPOS_CONFIGURATION/openvpn-needed ]; then
    echo """ Starting openVPN """
    /etc/init.d/openvpn start
    sleep 10
    ping6 -I tapVPN -c 2 $IPV6CHECK
    while [[ $? != 0 ]]; do
        ping6 -I tapVPN -c 2 $IPV6CHECK
    done
    # Ask slapos to use openvpn as ipv6 provider
    sed -i "/${SLAPVPN}/ s/# *//" $SLAPOS_CONFIGURATION/slapos.cfg
    # Use tapVPN as default interface for ipv6 traffic
    /sbin/ip -6 route del default dev br0
    sleep 2
else
    # OpenVPN not needed, comment line about he_ipv6 (if not ailready done)
    sed -i "/${SLAPVPN}/ s/^\([^#]\)/#\1/g" $SLAPOS_CONFIGURATION/slapos.cfg
fi



# set random root password
pwgen -sync 512 1 | passwd --stdin root

SLAP_INSTALL_LOG=/opt/slapos/slapos-install.log

while :; do
  if [ -f /opt/slapos/bin/slapformat ] && [ -f /opt/slapos/bin/bang ]; then
    # slapos tools available, nothing to do
    break
  fi
  # software not detected, force forever installation
  echo -n "Installing SlapOS, log availble at ${SLAP_INSTALL_LOG}..."
  mkdir -p /opt/slapos
  #(python -S -c \
  #  'import urllib2;print urllib2.urlopen("http://svn.zope.org/*checkout*/zc.buildout/trunk/bootstrap/bootstrap.py").read()' \
  #  | python -S - -c $SLAPOS_CONFIGURATION/software.cfg buildout:directory=/opt/slapos \
  #  >> ${SLAP_INSTALL_LOG} 2>&1 && /opt/slapos/bin/buildout -c \
  #  $SLAPOS_CONFIGURATION/software.cfg buildout:directory=/opt/slapos >> \
  #  ${SLAP_INSTALL_LOG} 2>&1 ) && (echo "done.") || (echo \
  #  "failed, retrying, the last error was:." ; tail -n 20 ${SLAP_INSTALL_LOG} ; rm -f /opt/slapos/bin/slapformat)
  rpm --install --force $SLAPOS_CONFIGURATION/slapos*.rpm
done

# Create PKI repository
repo=`egrep ^certificate_repository_path $SLAPOS_CONFIGURATION/slapos.cfg | sed 's/^certificate_repository_path.*= *//'`
mkdir -v -p -m 0755 $repo

# software detected, ready to run
# Set up cron
echo """# BEWARE: This file will be automatically regenerated on each boot
SHELL=/bin/sh
PATH=/usr/bin:/usr/sbin:/sbin:/bin:/usr/lib/news/bin
MAILTO=root
0 0 * * * root /opt/slapos/bin/slapformat --verbose --log_file=/opt/slapos/slapformat.log $SLAPOS_CONFIGURATION/slapos.cfg >> /opt/slapos/slapformat.log 2>&1
*/5 * * * * root /opt/slapos/bin/slapgrid-cp --verbose --logfile=/opt/slapos/slapgrid-cp.log --pidfile=/opt/slapos/slapgrid-cp.pid $SLAPOS_CONFIGURATION/slapos.cfg >> /opt/slapos/slapgrid-cp.log 2>&1
*/15 * * * * root /opt/slapos/bin/slapgrid-sr --verbose --logfile=/opt/slapos/slapgrid-sr.log --pidfile=/opt/slapos/slapgrid-sr.pid $SLAPOS_CONFIGURATION/slapos.cfg >> /opt/slapos/slapgrid-sr.log 2>&1
0 0 * * * root /opt/slapos/bin/slapgrid-ur --verbose --logfile=/opt/slapos/slapgrid-ur.log --pidfile=/opt/slapos/slapgrid-ur.pid $SLAPOS_CONFIGURATION/slapos.cfg >> /opt/slapos/slapgrid-ur.log 2>&1
0/10 * * * * root if [[ -f $SLAPOS_CONFIGURATION/openvpn-needed ]]; then ip -6 route del dev br0 ; fi
""" > /etc/cron.d/slapos-node

# Setup more server like network parameters in order to avoid
#    "Neighbour table overflow."
# Those machines are itself has a lot of interfaces and are in
# heavily networked environment, so limit of ARP cache for IPv4
# and IPv6 is 4x higher then default
# More tuning can be applied from: http://www.enigma.id.au/linux_tuning.txt
sysctl -w \
  net.ipv4.neigh.default.gc_thresh1=512 \
  net.ipv4.neigh.default.gc_thresh2=1024 \
  net.ipv4.neigh.default.gc_thresh3=2048 \
  net.ipv6.neigh.default.gc_thresh1=512 \
  net.ipv6.neigh.default.gc_thresh2=1024 \
  net.ipv6.neigh.default.gc_thresh3=2048

systemctl enable slapos-node.service
systemctl start slapos-node.service

# Increase default aio-max-nr for sql servers
sysctl -w fs.aio-max-nr=262144 

# Enable noop scheduler for disk which have SLAPOS labeled partition
disk=`blkid -L SLAPOS | sed -r -e 's/(\/dev\/|[0-9]*$)//g'`
echo noop > /sys/block/$disk/queue/scheduler

# Set kvm up
modprobe kvm_intel
sleep 1
chmod 666 /dev/kvm

# Set power saving
modprobe acpi_cpufreq

# Set hardware monitoring tools (for Shuttle xh61 machines)
modprobe coretemp
modprobe f71882fg

# Activate KSM (shared memory for KVM)
echo 1 > /sys/kernel/mm/ksm/run