#!/usr/bin/env bash

#Used to setup the nodes host OS (debian)
#This will NOT interact with each node, this is
#standalone, it will not try to link DRBD or sync anything
#across nodes, just basic setup after fresh debian install.
#mReschke 2012-04-03

this_script_dir="$( cd "$( dirname "$0" )" && pwd )"
source $this_script_dir/functions.sh
source /etc/nwq/cluster/cluster.conf

# Determine which node this is being run from
if [ "$HOSTNAME" == "$host1" ]; then
	is_node1=true
	host=$host1
	ip=$ip1
	port=$port1
elif [ "$HOSTNAME" == "$host2" ]; then
	is_node1=false
	host=$host2
	ip=$ip2
	port=$port2
else
	error "Hostname problems, check /etc/nwq/cluster/cluster.conf"
	exit 1
fi


function main() {
	# Display warnings and introduction text
	intro_text
	clearscreen

	header "Updating and Installing Software"
		line "Updating /etc/apt/sources.lst"
			create_apt_sources
		line "Upgrading Software"
			apt-get update
			apt-get upgrade --assume-yes
		line "Installing SSH Server"
			tasksel install ssh-server
		line "Installing System Utilities"
			apt-get install sudo rsync curl vim htop iotop multitail \
				nmap kpartx parted gdisk smartmontools hdparm ntfsprogs \
				sysstat pacemaker ntp ntpdate bridge-utils ethtool \
				ifenslave-2.6 python subversion \
				--assume-yes
		line "Installing Development Tools"
			apt-get install build-essential libncurses5-dev flex --assume-yes
		line "Installing DRBD"
			apt-get install drbd8-utils --assume-yes
		line "Installing Virtualization Platform"
			install_virt
		line "Cleaning Software"
			apt-get autoclean --assume-yes



	header "Configuring the System"
		line "Configuring Hosts File"
			configure_hosts
		line "Configuring ssh"
			configure_ssh
		line "Configuring sudo"
			echo "toor    ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers
		line "Configuring vim"
			configure_vim
		line "Configuring Network Interfaces"
			configure_network
		line "Configuring DRBD"
			configure_drbd
        line "Configuring Virtualization"
            configure_virt
		line "Configureing Pacemaker"
			configure_pacemaker

	echo
	echo "All Done!"
    echo "You should reboot then join the nodes together"
    echo "with the join-host.sh script"
	echo
	echo "Bye!"

}

function install_virt() {
    echo
    echo "Which virtualization technology are you going to use?"
    echo "The Loadbalancer/Data store uses Xen which the web/sql servers probably use KVM"
    echo
    while [ "$virt" != "kvm" -o "$virt" != "xen" ]; do
        echo -n "Xen or KVM (use lowercase)? (kvm/xen): "; read virt
    done
    
    if [ "$virt" == "xen" ]; then
        if $is_squeeze; then
            line "Installing Xen for Squeeze"
            aptitude -P install xen-linux-system --assume-yes
            apt-get install xen-qemu-dm-4.0 linux-headers-$(uname -r) xen-tools --assume-yes
        else
            line "Installing Xen for Wheezy"
            aptitude -P install xen-linux-system --assume-yes
            apt-get install linux-headers-$(uname -r) xen-tools --assume-yes            
        fi    
    else
        line "Installing KVM"
        apt-get install kvm qemu-kvm virtinst --assume-yes
    fi


}


function configure_pacemaker() {
	if $is_node1; then
		echo
		notice "I am going to generate the corysync auth key now, just press keys\non the keyboard untill the entrophy is generated."
		corosync-keygen
	fi
	sed -i 's/bindnetaddr: 127.0.0.1/bindnetaddr: 10.10.10.0/g' /etc/corosync/corosync.conf
}

function configure_virt() {
    if [ "$virt" == "xen" ]; then
        line "Configuring Xen"
        if $is_squeeze; then
            sed -i "s/GRUB_DEFAULT=0/GRUB_DEFAULT=4/g" /etc/default/grub
        else
            sed -i "s/GRUB_DEFAULT=0/GRUB_DEFAULT=2/g" /etc/default/grub
        fi
        sed -i 's#XENDOMAINS_SAVE=/var/lib/xen/save#XENDOMAINS_SAVE=""#g' /etc/default/xendomains
        sed -i 's#XENDOMAINS_RESTORE=true#XENDOMAINS_RESTORE=false#g' /etc/default/xendomains
    else
        line "Configuring KVM"
        adduser `id -un` libvirt
        adduser `id -un` kvm
    fi
    
    sed -i "s/^loop/#loop/g" /etc/modules
    echo "loop max_loop=64" >> /etc/modules
    update-grub
}


function configure_drbd() {
	#update-rc.d -f drbd remove
	insserv -f drbd --remove
	mv /etc/drbd.d/{global_common.conf,.global_common-orig.conf}

    echo "options drbd disable_sendpage=1" > /etc/modprobe.d/drbd.conf

	#Copy default DRBD configs and the 3 main resource configs
	cp -rf /etc/nwq/cluster/defaults/etc/drbd.d/* /etc/drbd.d/

	sed -i "s/on node1/on $host1/g" /etc/drbd.d/data.res
	sed -i "s/on node2/on $host2/g" /etc/drbd.d/data.res

	sed -i "s/on node1/on $host1/g" /etc/drbd.d/xennode1.res
	sed -i "s/on node2/on $host2/g" /etc/drbd.d/xennode1.res
	
	sed -i "s/on node1/on $host1/g" /etc/drbd.d/xennode2.res
	sed -i "s/on node2/on $host2/g" /etc/drbd.d/xennode2.res

}



function configure_vim() {
cat >> /etc/vim/vimrc << "EOF"
set tabstop=4
set ts=4
set sw=4
"expandtab sets tabs to spaces
"set expandtab
set nowrap
syntax enable
set autoindent
set foldmethod=manual
let php_folding = 1
set ignorecase
"set nu! "Line Numbers
set guioptions+=b "Bottom Scroll Bar for gVim
"set mouse=a
EOF
}


function configure_ssh() {
	sed -i "s/Port 22/Port 22\nPort $port/g" /etc/ssh/sshd_config

	notice "I am setting up the ssh keys, just use the defaults here, don't enter a passphrase"
	ssh-keygen; su -l toor -c 'ssh-keygen'

}

function configure_hosts() {
	echo "" >> /etc/hosts
	echo -e "$ip1\t$host1" >> /etc/hosts
	echo -e "$ip2\t$host2" >> /etc/hosts
}



function configure_network() {

cat > /etc/resolv.conf << "EOF"
# If the xenlb is running, use this DNS server
nameserver 10.0.0.10

# If the xenlb is NOT running, use our ISP's DNS server
#nameserver 216.136.95.2
#nameserver 64.132.94.250
EOF

cat > /etc/network/interfaces << "EOF"
# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).

# The loopback network interface
auto lo
iface lo inet loopback

# The primary network interface
auto eth0
iface eth0 inet manual

# Bridge interface
auto br0
iface br0 inet static
	address replacemewithip
	netmask 255.255.248.0
	network 10.0.0.0
	broadcast 10.0.7.255
	gateway 10.0.0.1
	bridge_ports eth0
EOF
    sed -i "s/replacemewithip/$ip/g" /etc/network/interfaces
    if $use_bond0; then
cat >> /etc/network/interfaces << "EOF"

# Bond eth1,eth2 Interface
auto bond0
iface bond0 inet static
	address replacemewithip
	netmask 255.255.255.0
	slaves eth1 eth2
	bond-mode balance-rr
	bond-miimon 100
	bond-downdelay 200
	bond-updelay 200
	mtu 9000
EOF
    fi
    if $is_node1; then
    	sed -i "s/replacemewithip/10.10.10.11/g" /etc/network/interfaces
    else
    	sed -i "s/replacemewithip/10.10.10.12/g" /etc/network/interfaces
    fi
    #/etc/init.d/networking restart
    #ifconfig eth0 up
}



function create_apt_sources() {

    if [ "$(cat /etc/apt/sources.list|grep wheezy)" != "" ]; then
        # Running Wheezy
		line "Running Wheezy"
        is_squeeze=false
cat > /etc/apt/sources.list << "EOF"
deb http://ftp.us.debian.org/debian/ wheezy main contrib non-free
deb-src http://ftp.us.debian.org/debian/ wheezy main contrib non-free

deb http://security.debian.org/ wheezy/updates main
deb-src http://security.debian.org/ wheezy/updates main
EOF
    else
        # Running Squeeze
		line "Running Squeeze"
        is_squeeze=true
cat > /etc/apt/sources.list << "EOF"
deb http://ftp.us.debian.org/debian/ squeeze main
deb-src http://ftp.us.debian.org/debian/ squeeze main

deb http://security.debian.org/ squeeze/updates main
deb-src http://security.debian.org/ squeeze/updates main

# squeeze-updates, previously known as 'volatile'
# A network mirror was not selected during install.  The following entries
# are provided as examples, but you should amend them as appropriate
# for your mirror of choice.
deb http://ftp.debian.org/debian/ squeeze-updates main
deb-src http://ftp.debian.org/debian/ squeeze-updates main
EOF
    fi
}


function intro_text() {
	clearscreen
	echo -e "${RED}"
	echo "READ CAREFULLY BEFORE YOU CONTINUE:"
	echo -e "${LIGHTRED}"
	echo "You MUST verify that /etc/nwq/cluster/cluster.conf is setup properly for these nodes!"
	echo -e "${DEFAULT}"

	echo "This script is meant to be executed on both nodes (not necessarily at the same time)"
    echo "just after a fresh install of either Debian Squeeze or Debian Wheezy.  This script will"
    echo "update to wheezy and install/configure all cluster utilities.  This script will NOT"
    echo "sync up the nodes, no ssh keys will be exchanged, no DRBD linked...  That means this"
    echo "script can be run standalone, you can run this on a degraded node, the other ndoe does not"
    echo "have to be setup at the same time.  Once all nodes are setup and ready to sync, there is"
    echo "another script (join-host.sh) in /usr/local/bin/cluster/"
	echo
	echo "To continue installation please type 'begin'"
	echo
	echo -n "<>>(#)> "; read begin

	if [ "$begin" != "begin" ]; then
		echo
		echo "Fine, bye then :("
		echo
		exit 0
	fi
}

virt=kvm
is_squeeze=true
main
