#!/usr/bin/env bash

#This is for the LB/Store Nodes ONLY!
#Nodes assumed to have Asus Sabertooth motherboard
#with the Athlon FX 8-core CPU and the 2x 3TB Hard drives

#This installs the pre-configured debian testing (wheezy)
#distro created by mReschke 2012-04-06 for LB/Store nodes

#CAUTION: THIS WILL WIPE ALL DATA FROM ALL DRIVES!!

#mReschke 2012-04-06

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 "Configuring Drives"
		line "Creating GPT Partitions"
			##create_partitions
		line "Creating Filesystems"
			##create_filesystems

	header "Extracting Root Filesystem"
		line "Mounting /dev/vg0/root"
			##mkdir /newroot
			##mount /dev/vg0/root /newroot
		line "Extracting root-xen-wheezy.tar.gz"
			##extract_root
		line "Preparing chroot Environment"
			##prepare_chroot
	
	header "Configuring System Files"
		line "Configure apt-get sources"
			##configure_apt_sources
		line "Configure manup"
			##configure_manup
		line "Configure ssh"
			##configure_ssh
		line "Configure drbd"
			##configure_drbd
		line "Configure Other"
			##configure_other

	header "Re-Installing All Packages"
		line "Re-Installing All Packages from Local Cache"
			###################################reinstall_apt
		line "Installing Grub"
			#install_grub

	header "Finalizing Installation"
		line "Configure Networking LAST"
			#NOTE do this last, will loose internet connection inside chroot
			configure_network
		line "Cleanup"
			cleanup

	echo
	echo "All Done! Have Fun!"
	echo "You may reboot the computer now, and hope it works :)"
	echo
	echo "Bye!"

}

function cleanup() {
	cd ~
	chrootcmd "vgchange -an vg0"
	umount /newroot/dev/shm
	umount /newroot/dev/pts
	umount /newroot/dev
	umount /newroot/sys
	umount /newroot/proc
	umount /newroot
}

function reinstall_apt() {
	# Must do one at a time like this because if you group them in one command and one package fails, entire apt-get command fails
	#Dont think this is needed
	#chrootcmd "for pkg in \$(dpkg --get-selections | cut -f1); do apt-get install \$pkg --reinstall --assume-yes; done"
}

function install_grub() {
	for drive in $drives; do
		drive=/dev/sda #TESTING SAVE USB
		chrootcmd "grub-install --recheck $drive"
	done
	chrootcmd "update-grub"
}

function configure_manup() {
	chrootcmd "manup sync; manup install manup/manup --noconfirm; manup install nwq/dynatron-cluster-framework --noconfirm"
}

function configure_other() {
	# Uncommend sdb2 swap if required
	for drive in $drives; do
		if [ "$drive" == "/dev/sdb" ]; then
			sed -i "s|#/dev/sdb2|/dev/sdb2|g" /newroot/etc/fstab
		fi
	done

	# Grub Default
	#sed -i "s/GRUB_DEFAULT=0/GRUB_DEFAULT=2/g" /newroot/etc/default/grub


}



function chrootcmd() {
	# Execute one command inside the chroot then exit the chroot
	chroot /newroot /usr/bin/env -i HOME=/root TERM="$TERM" PATH="/usr/local/sbin:/usr/sbin:/sbin:/usr/local/bin:/usr/bin:/bin" /bin/bash -c "$*"
}


function prepare_chroot() {
	cp -rav /etc/mdadm.conf /newroot/etc/
	cp -rav /etc/resolv.conf /newroot/etc/
	cp -rav /etc/nwq/cluster/cluster.conf /newroot/etc/nwq/cluster/

	mount -v --bind /dev /newroot/dev
	mount -vt devpts devpts /newroot/dev/pts
	mount -vt tmpfs shm /newroot/dev/shm
	mount -vt proc proc /newroot/proc
	mount -vt sysfs sysfs /newroot/sys
	
	chrootcmd "vgscan"
	#chrootcmd "vgchange -ay vg0"
}
	

function extract_root() {
	echo "Enter the full path to the root-xen-wheezy.tar.gz file"
	echo "This should be on the USB drive you inserted and mounted (or wherever)"
	echo "DONT include the actual filename.tar.gz just the folder path"
	echo "Example: /mnt/"
	echo
	echo -n "Root tar.gz file: "; read tarpath

	if [ -e "$tarpath" ]; then
		cp -var ${tarpath}/root-xen-wheezy.tar.gz /newroot/
		cd /newroot
		tar -zxvpf root-xen-wheezy.tar.gz
		rm -rf root-xen-wheezy.tar.gz
		cd ~
	else
		extract_root
	fi


}

function create_filesystems() {
	for drive in $drives; do
		drive=/dev/sda #TESTING SAVE USB
		mkswap ${drive}2
		modprobe raid1
		modprobe dm-mod
		mdadm --create /dev/md0 homehost=md --level=1 --raid-devices=2 /dev/sda3 missing
		mdadm --misc --detail /dev/md0
		pvcreate -ff /dev/md0
		vgcreate vg0 /dev/md0
		lvcreate -L 16G vg0 -n root
		lvcreate -L 128G vg0 -n xennode1
		lvcreate -L 128G vg0 -n xennode2
		lvcreate -L 32G vg0 -n xenswap
		lvcreate -L 500G vg0 -n data
		#lvcreate --extents 100%FREE vg0 -n data
		vgscan
		mdadm --examine --scan > /etc/mdadm.conf
		
		mkfs.ext3 -m5 /dev/vg0/root
		mkfs.ext3 -m0 /dev/vg0/xenswap
		#vg0/xennode1 and xennode2 and data are not formated, they will be DRBD soon!
	done
}

function create_partitions() {
	echo "Enter the drives you want to partition, they will be partitioned exactly the same."
	echo "sdx1 256MB for UEFI bios"
	echo "sdx2 4GB for swap"
	echo "sdx3 Remainder for RAID device used to store all Logical Volumes (root, xennode1...)"
	echo
	echo "Enter full paths, separated by spaces, ex: /dev/sda /dev/sdb"
	echo "DO NOT put a slash after them. At most there should really only be 2 entered here"
	echo
	echo -n "Drives to partition: "; read drives
	echo $drives

	# Disable existing raid first
	for md in $(ls /dev/|grep md); do
		if [ ! -d "/dev/$md" ]; then
			mdadm --manage --stop /dev/$md
		fi
	done
	
	for drive in $drives; do
		drive=/dev/sda #TESTING SAVE USB

		line "Partitioning $drive"
		parted $drive -- mklabel gpt
		vgscan
		parted $drive -- unit s mkpart biosboot 8192 16383
		parted $drive -- set 1 bios_grub on
		parted $drive -- unit s mkpart primary 16384 4G
		parted $drive -- mkpart primary 4G 100%
		parted $drive -- set 3 raid on
		parted $drive -- print
	done

	echo
	echo "Does it look like the partition creation was a success?"
	echo "If not don NOT continue this script"
	echo 
	echo -n "Continue Installation? (y/N): "; read cont
	if [ "$cont" == "y" ]; then
		echo
	else
		echo "Partition failed, fix and rerun this script"
		exit 1
	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
	#sed -i 's/no/yes/g' /etc/default/corosync

	#service corosync start
	#sleep 5
	#crm configure show

	#echo
	#notice "Pacemaker is ready for you to setup, I will NOT configure it here"
	#echo
	#sleep 3
	echo ""

}



function configure_drbd() {
	#Already done in root .tar.gz
	#cat > /etc/modprobe.d/drbd.conf << "EOF"
	#options drbd disable_sendpage=1
	#EOF

	#Copy default DRBD configs and the 3 main resource configs
	mv /newroot/etc/drbd.d/{global_common.conf,.global_common-orig.conf}
	cp -rf /newroot/etc/nwq/cluster/defaults/etc/drbd.d/* /newroot/etc/drbd.d/

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

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

	if ! $node_degraded; then
		clearscreen
		echo "I am about to create DRBD metadata and start syncing"
		echo "You should wait until both nodes are at this point, then continue"
		echo 
		echo -n "Press enter to continue"; read tmp
	
		drbdadm create-md all

		echo "DRBD metadata has been created on this node, make sure its has been created"
		echo "on the other node too, both nodes shold be at this prompt!"
		echo
		echo -n "Press enter to continue"; read tmp

		service drbd start

		if $is_node1; then
			drbdadm -- --overwrite-data-of-peer primary all
			drbdadm primary all
		fi

		echo "At this point DRBD should be syncing all 3 devices"
		echo "You can run: watch cat /proc/drbd"
		echo "On each node to watch the progress.  You do NOT have to wait"
		echo "for the initial sync to finish before you can continue, you may continue"
		echo "at any time"
		echo
		echo "Press enter to continue formatting these devices"; read tmp

		if $is_node1; then
			mkfs.ext3 -m0 /dev/drbd1
			mkfs.ext3 -m0 /dev/drbd2
			mkfs.ext3 -m0 /dev/drbd0
			drbdadm secondary all
			echo
			echo "Ok formatting done, node2 should be waiting for you"
			echo "Go ahead and continue on each node"
			echo
			echo "Press enter to continue"; read tmp
		else
			drbdadm secondary all
			echo "At this piont the primary node should be formatting the drives"
			echo "You should wait here (on this node2) until the formats on node1 are complete"
			echo
			echo "Press enter to continue (once formatting is done on node1)"; read tmp
		fi

		if $is_node1; then
			drbdadm primary xennode1
		else
			drbdadm primary data
			drbdadm primary xennode2
		fi
	fi
}


function configure_ssh() {
	sed -i "s/Port 22/Port 22\nPort $port/g" /newroot/etc/ssh/sshd_config
	
	#move to another script, the sync node script...
	#clearscreen
	#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'
	#clearscreen
	#notice "I am copying these ssh keys to the other nodes, just keep entering the root and toor passwords for me"
	#if $is_node1; then
	#	ssh-copy-id toor@$host2
	#	ssh-copy-id root@$host2
	#	su -l toor -c "ssh-copy-id toor@$host2"
	#	su -l toor -c "ssh-copy-id toor@$host2"
	#else
	#	ssh-copy-id toor@$host1
	#	ssh-copy-id root@$host1
	#	su -l toor -c "ssh-copy-id toor@$host1"
	#	su -l toor -c "ssh-copy-id toor@$host1"
	#fi
	#notice "Done - SSH keys created and exchanged"
	#sleep 2
	#clearscreen
}



function configure_network() {
	# Configure Hostname
	echo "$host" > /newroot/etc/hostname
	sed -i "s/node1/$host/g" /newroot/etc/hosts
	chrootcmd "hostname $host"
	echo "" >> /newroot/etc/hosts
	echo -e "$ip1\t$host1" >> /newroot/etc/hosts
	echo -e "$ip2\t$host2" >> /newroot/etc/hosts

cat > /newroot/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 > /newroot/etc/network/interfaces << "EOF"
# 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" /newroot/etc/network/interfaces
if $use_bond0; then
cat >> /newroot/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" /newroot/etc/network/interfaces
	else
		sed -i "s/replacemewithip/10.10.10.12/g" /newroot/etc/network/interfaces
	fi
}



function configure_apt_sources() {
cat > /newroot/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

# squeeze-updates, previously known as 'volatile'
deb http://ftp.us.debian.org/debian/ squeeze-updates main
deb-src http://ftp.us.debian.org/debian/ squeeze-updates main
EOF
}

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 is for the LB/Store Nodes ONLY! Nodes assumed to have Asus Sabertooth motherboard"
	echo "with the Athlon FX 8-core CPU and the 2x 3TB Hard drives. This installs the pre-configured debian testing (wheezy)"
	echo "distro created by mReschke 2012-04-06 for LB/Store nodes. Run this on both nodes to get their dom0 host setup!"
	echo "This installer can work with only 1 hard drive (software raid degraded)"
	echo
	echo -e "${RED}CAUTION: THIS WILL WIPE ALL DATA FROM DRIVES YOU SPECIFY!!!${DEFAULT}"
	echo "Be sure not to specify your USB drive as a drive to delete!! ha! If your raid is degraded then sdb"
	echo "Will probably be your USB drive, so be careful. Make sure you have all your xen VM's, configs,"
	echo "and main data partitions or .img files backed up!!!"
	echo
	echo "mReschke 2012-04-06"
	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
}

drives=(/dev/sda)
main


