#!/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.
#
##############################################################################


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

IPV6CHECK=ipv6.google.com

# Test ipv6 connectivity and if not working use openvpn 
# and wait for it to be ready
/etc/init.d/openvpn stop
ping6 -c 2 $IPV6CHECK
if [[ $? != 0 ]]; then
    echo """ Starting openVPN """
    /etc/init.d/openvpn start
    ping6 -c 2 $IPV6CHECK
    while [[ $? != 0 ]]; do
        ping6 -c 2 $IPV6CHECK
    done
    # Ask slapos to use openvpn as ipv6 provider                                                                                                                       
    if [ ! -f /etc/slapos/openvpn-needed ]; then
        touch /etc/slapos/openvpn-needed
        echo "ipv6_interface = tapVPN" >> /etc/slapos/slapos.cfg
    fi
else
    # OpenVPN not needed delete last line of slapos.cfg if OpenVPN has been used before                                                                                     
    if [ -f /etc/slapos/openvpn-needed ]; then
        rm /etc/slapos/openvpn-needed
        sed -i '$d' /etc/slapos/slapos.cfg
    fi
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 /etc/slapos/software.cfg buildout:directory=/opt/slapos \
    >> ${SLAP_INSTALL_LOG} 2>&1 && /opt/slapos/bin/buildout -c \
    /etc/slapos/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)
done

# Create PKI repository
repo=`egrep ^certificate_repository_path /etc/slapos/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 /etc/slapos/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 /etc/slapos/slapos.cfg >> /opt/slapos/slapgrid-cp.log 2>&1
*/5 * * * * root /opt/slapos/bin/slapgrid-sr --verbose --logfile=/opt/slapos/slapgrid-sr.log --pidfile=/opt/slapos/slapgrid-sr.pid /etc/slapos/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 /etc/slapos/slapos.cfg >> /opt/slapos/slapgrid-ur.log 2>&1
""" > /etc/cron.d/slapos

# 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

# Execute slapformat
echo -n "Running slapformat..."
/opt/slapos/bin/slapformat --verbose --console /etc/slapos/slapos.cfg
echo "done."
echo -n "Banging..."
/opt/slapos/bin/bang -m "Rebooted" /etc/slapos/slapos.cfg
echo "done."

# 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
chmod 666 /dev/kvm