#!/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
if [ ! -f $SLAPOS_CONFIGURATION/openvpn-needed ]; then
    /etc/init.d/openvpn stop
fi

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

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

while :; do
  if [ -f /opt/slapos/bin/slapformat ] && [ -f /opt/slapos/bin/bang ]; then
      zypper search -i slapos.node | grep slapos.node > /dev/null
      if [ $? != 0 ]; then
        echo -n "Installing SlapOS"
        zypper --gpg-auto-import-keys install -fy slapos.node
      fi
    # slapos tools available, nothing to do
    break
  fi
  # software not detected, force forever installation
  echo -n "Installing SlapOS"
  zypper --gpg-auto-import-keys install -fy slapos.node
done

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


# Fix path in case of old config:
SLAPOS_GOOD_CONFIGURATION=/etc/opt/slapos/
if [ $SLAPOS_GOOD_CONFIGURATION != $SLAPOS_CONFIGURATION ]; then
    sed -i "s|$SLAPOS_GOOD_CONFIGURATION|$SLAPOS_CONFIGURATION|g" /etc/cron.d/slapos-node
    sed -i "s|$SLAPOS_GOOD_CONFIGURATION|$SLAPOS_CONFIGURATION|g" /usr/sbin/slapos-start
fi

# Set up cron
let HOUR=$RANDOM%%23;
let MINUTE=$RANDOM%%60;

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=""

$MINUTE $HOUR * * * root /usr/local/bin/slapupdate -v --slapos-configuration $SLAPOS_CONFIGURATION/slapos.cfg >> /opt/slapos/slapupdate.log 2>&1

"""> /etc/cron.d/slapos

if [ -f ${SLAPOS_CONFIGURATION}/SlapContainer-needed ]; then
    echo """
# XXX: SlapContainer
*/5 * * * *	root	if [ -x /opt/slapgrid/843c2b4de8c5579427b072d00ec2ec9e/bin/slapcontainer ] ; then /opt/slapgrid/843c2b4de8c5579427b072d00ec2ec9e/bin/slapcontainer --pid /opt/slapos/slapcontainer.pid ${SLAPOS_CONFIGURATION}slapos.cfg /opt/slapos/slapcontainer.db > /opt/slapos/slapcontainer.log 2>&1 ; fi
""" >> /etc/cron.d/slapos
fi

# 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

# software detected, ready to run
systemctl enable slapos-node.service
systemctl start slapos-node.service

# Increase default aio-max-nr for sql servers
sysctl -w fs.aio-max-nr=16777216
# Increase semaphore limits
sysctl -w kernel.sem="1250 256000 100 1024"

# Force reboot after kernel panic
sysctl -w kernel.panic=120

# 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 > /dev/null  2>&1

# Set hardware monitoring tools (for Shuttle xh61 machines)
modprobe coretemp > /dev/null  2>&1
modprobe f71882fg > /dev/null  2>&1

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