#!/bin/bash
# Program:
#   DRBL virt module
# Author: 
#   Jazz, Rock {jazz, rock}@nchc.org.tw
# Version:
#    1.0
# History:
#   2010/07/20  Rock    First release (1.0)

# [Variable Declation]
cpu_flag="no"
Linux_bit=""
Linux_Distribution=""
Linux_Version=""
VMM_select=""


# [Check Root]
function check_root(){      
  if [ $USER != "root" ]; then
    echo -e "Please change root to run it!"
    exit
  fi
} 

# [Change root to run]
function check_root_run(){
    if [ $USER != "root" ]; then
    echo -e "Please change root to run it!"
    sudo su -c ~/"$0" "$@"
    exit
fi
}


# [Check CPU support]
function cpu_check(){
egrep '(vmx|svm)' --color=always /proc/cpuinfo > /dev/null
if [ $? == 0 ]; then
    cpu_flag="yes"
fi
}


# [Check System Version]
function check_systemInfo(){
Linux_bit=$(uname -m)
Linux_Distribution=$(lsb_release -i | awk '{print $3}')
Linux_Version=$(lsb_release -r | awk '{print $2}')
}


# [Select Hypervisior(Xen/KVM)]
function VMM_select(){
echo ""
if [ $cpu_flag == "yes" ]; then
    while [ "$VMM_select" != "1" -a "$VMM_select" != "2"  ]
    do
       read -p "Which VMM/Hypervisior will be used in DRBL (1)Xen (2)KVM: " VMM_select
    done
	if [ $VMM_select == "1"  ]; then
	  echo "Xen" > $Work_Home/etc/hypervisior
	else
	  echo "KVM" > $Work_Home/etc/hypervisior
	fi	
else
    echo "Xen will be the only Hypervisior in your DRBL"
    echo -e "Because CPU don't support virtualization, it can't choose KVM to be the Hypervisior"
    read -p "push [enter] to contiunte..."
    VMM_select=1
    echo "Xen" > $Work_Home/etc/hypervisior
fi  
}   


# [Check Hypervisior]
function check_hypervisior(){
    hypervisior=$(cat $Work_Home/etc/hypervisior)    
}


# [Check Debian Xen package]
function check_debian_xen(){
echo "[Check Xen package in apt server]"
echo ""
aptitude update
check_debian_xen_pkg=$(aptitude search xen-linux-system)
if [ -n "$check_debian_xen_pkg"  ]; then
    check_debian_xen_pkg="yes"
else
    check_debian_xen_pkg="no"
fi
}


# [Check Xen kernel]
function check_xen_nu(){
Kernels=$(ls /boot | grep vmlinuz)
declare -i Kernels_nu=$(echo $Kernels | wc -w)
Kernel_choose=""

Xens=$(ls /boot | grep -i ^xen)
declare -i Xen_nu=$(echo $Xen | wc -w)
Xen_choose=""

jude="no"

while [ $jude != "yes" -a $jude != "y" ]
do
    declare -i i=1
    declare -i j=1
    echo ""
    echo "[Choose Xen-enabled Kernel]"
    if [ $Kernels_nu -gt 1  ]; then
        for Kernel in $Kernels
        do
            echo "($i) $Kernel" 
            i=i+1
        done

        read -p "Xen Kenrel is (1/2/...): " Kernel_choose
        Xen_Kernel=$(echo $Kernels | cut -d " " -f${Kernel_choose})

    else
        Xen_Kernel=$Kernels
    fi

    if [ $Xen_nu -gt 1  ]; then
        for Xen in $Xens
        do
            echo "($i) $Xen"
            j=j+1
        done

        read -p "Xen is (1/2/...): " Xen_choose
        Xen=$(echo $Xens | cut -d " " -f${Xen_choose})
    else
        Xen=$Xens
    fi

    read -p "Are you sure (yes/no): " jude
done

#echo "debug: Xen_Kernel=$Xen_Kernel"
}


# [Tunning Debain env for Xen]
function debain-lenny_xen_patch(){
echo xen.independent_wallclock=1 >> /etc/sysctl.conf
echo loop max_loop=255 >> /etc/modules
echo xenblktap >> /etc/modules
ln -s /usr/lib/$/bin/tapdisk /usr/sbin
}


# [Get ethX for DRBL environment usage ]
function get_DRBL_eth(){
eths=$(ls /etc/drbl | grep macadr-eth[0-9] | grep [0-9].txt$ | cut -d "-" -f2 | cut -d "." -f1)
eths_nu=$(echo $eths | wc -w)

if [ $eths_nu -gt 1 ]; then
    echo ""
    echo "There are multiple eth for DRBL environment: "
    echo "$eths"
fi

}


# [Get DRBL client IP range]
function get_Host_IP_range(){
if [ ! -e /usr/bin/ipcalc ] || [ ! -e /opt/drbl/bin/drbl-get-network ] || [ ! -e /opt/drbl/bin/drbl-get-ipadd ]; then
    echo "Don't find /usr/bin/ipcalc /opt/drbl/bin/drbl-get-network & /opt/drbl/bin/drbl-get-ipadd"
    exit 0
fi

# get eth network X.X.X
eth_network_f3=$(echo $eth_network | cut -d "." -f 1-3)

IP_nu=$(cat /etc/drbl/IP_HOST_TABLE | grep $eth_network_f3 | wc -l)
Host_first_IP=$(cat /etc/drbl/IP_HOST_TABLE | grep $eth_network_f3 | awk "NR==1 {print $1}" | awk '{print $1}')
Host_last_IP=$(cat /etc/drbl/IP_HOST_TABLE | grep $eth_network_f3 | awk "NR==$IP_nu {print $1}"| awk '{print $1}')

}


# [Input VM IP range]
function get_VM_IP_range_and_prefix_name(){
echo ""
echo "[Setup VM IP range]"
echo "DRBL client IP range -> $eth: [$Host_first_IP ~ $Host_last_IP]"

Host_last_IP_4=$(echo $Host_last_IP | cut -d "." -f4)
Host_last_IP_4=$(($Host_last_IP_4+1))
VM_first_IP=$(echo $Host_last_IP | cut -d "." -f 1-3)
VM_first_IP="${VM_first_IP}.${Host_last_IP_4}"

echo "The VM IP Range will start from -> [$VM_first_IP]"
jude="no"
while [ $jude != "yes" -a $jude != "y" ];
do
    echo ""
    echo "Input VM number/IP range for $eth (ex. 40)."

    jude_2="no"
    while [ $jude_2 != "yes" -a $jude_2 != "y" ]
    do
        jude_2="yes"
        read -p "(If you have 10 PCs(4-core), suggestion is 30): " VM_IP_range
        if [ $((${VM_IP_range}+${Host_last_IP_4})) -ge 254 ]; then
            echo "range can't greater than 254"
            jude_2="no"
        fi
    done

    #read -p "Input Prefix name for VM for $eth (ex. drblvm): " VM_prefix_name
    VM_prefix_name=$(cat /etc/drbl/drblpush.conf  | grep hostname= | sed 's/hostname=//')
    read -p "Is it correct? (yes/no): " jude
done

#echo "VM_first_IP=$VM_first_IP"
#echo "VM_IP_range=$VM_IP_range"
}


# [Get VM prefix name]
#function get_VM_prefix_name(){ 
#jude="no"
#while [ $jude != "yes" -a $jude != "y" ];
#do
#    echo ""
#    read -p "Input Prefix name for VM for $eth (ex. drblvm): " VM_prefix_name
#    read -p "Is it correct? (yes/no): " jude
#done
#echo "VM_prefix_name=$VM_prefix_name"
#}


# [Create VM IP table]
function create_VM_IP_table(){
#/etc/drbl-virt/etc/IP_VM_eth
VM_prefix_eth=$(echo $eth |  sed 's/eth//g')
VM_Host_totoal_nu=$((${Host_last_IP_4}-1+${VM_IP_range}))
if [ -e /opt/drbl-virt/etc/IP_VM_$eth ]; then
    mv -f /opt/drbl-virt/etc/IP_VM_$eth /opt/drbl-virt/etc/IP_VM_${eth}.$(date +%Y-%m-%d-%H-%M-%S).drbl-virt_bak
fi
declare -i VM_IP_0=$VM_prefix_eth
declare -i VM_IP_1=""
declare -i VM_IP_2=""
declare -i VM_IP_3=""

# 2 bit
if [ $VM_Host_totoal_nu -lt 100 ]; then
    for (( i=$Host_last_IP_4 ; i<="$VM_Host_totoal_nu" ; i++ ))
    do
        if [ $i -lt 10 ]; then
            VM_IP_1=0
            VM_IP_2=$i
            echo "${eth_network_f3}.$VM_IP_2 ${VM_prefix_name}${VM_IP_0}${VM_IP_1}${VM_IP_2}" >> /opt/drbl-virt/etc/IP_VM_$eth
        else
            VM_IP_1=$i
            echo "${eth_network_f3}.$VM_IP_1 ${VM_prefix_name}${VM_IP_0}${VM_IP_1}" >> /opt/drbl-virt/etc/IP_VM_$eth
        fi
    done
# 3 bit
elif [ $VM_Host_totoal_nu -ge 100 ] && [ $VM_Host_totoal_nu -lt 254 ]; then
    for (( i=$Host_last_IP_4 ; i<=$VM_Host_totoal_nu ; i++ ))
    do
        if [ $i -lt 10 ]; then
            VM_IP_1=0
            VM_IP_2=0
            VM_IP_3=$i
            echo "${eth_network_f3}.${VM_IP_3} ${VM_prefix_name}${VM_IP_0}${VM_IP_1}${VM_IP_2}${VM_IP_3}" >> /opt/drbl-virt/etc/IP_VM_$eth
        elif [ $i -ge 10 ] && [ $i -lt 100 ]; then
            VM_IP_1=0
            VM_IP_2=$i
            echo "${eth_network_f3}.${VM_IP_2} ${VM_prefix_name}${VM_IP_0}${VM_IP_1}${VM_IP_2}" >> /opt/drbl-virt/etc/IP_VM_$eth
        else
            VM_IP_1=$i
            echo "${eth_network_f3}.${VM_IP_1} ${VM_prefix_name}${VM_IP_0}${VM_IP_1}" >> /opt/drbl-virt/etc/IP_VM_$eth
        fi
    done

fi
}


# [Creat VM Mac table]
function generate_Xen_MAC_address(){
#echo "eth $eth"
#echo "VM_Host_totoal_nu $VM_Host_totoal_nu"
#echo "Host_last_IP_4 $Host_last_IP_4"
#echo "VM_prefix_eth $VM_prefix_eth"

# /opt/drbl-virt/etc/macadr-VM-ethX.txt
# MAC address [00:16:3e:xx:xx:xx] is for Xen use
declare -i Xen_MAC_1="0"
declare -i Xen_MAC_2="$VM_prefix_eth"
declare -i Xen_MAC_3="0"
declare -i Xen_MAC_4="0"
Xen_MAC_5=""
Xen_MAC_6=""
VM_Host_totoal_nu=$(cat $Work_Home/etc/IP_VM_$eth | wc -l)

# backup
if [ -e /opt/drbl-virt/etc/macadr-VM-$eth.txt ]; then
mv -f /opt/drbl-virt/etc/macadr-VM-$eth.txt /opt/drbl-virt/etc/macadr-VM-$eth.txt.$(date +%Y-%m-%d-%H-%M-%S).drbl-virt_bak
fi

# generate MAC
for (( i=1 ; i<="$VM_Host_totoal_nu" ; i++ ))
do
    if [ $i -lt 10 ]; then
        Xen_MAC_5=0
        Xen_MAC_6=$i
        echo "00:16:3e:${Xen_MAC_1}${Xen_MAC_2}:${Xen_MAC_3}${Xen_MAC_4}:${Xen_MAC_5}${Xen_MAC_6}" >> /opt/drbl-virt/etc/macadr-VM-$eth.txt
    elif [ $i -ge 10 ] && [ $i -le 15 ] ; then
        Xen_MAC_5=0
        # translate 10(dec) to 16(hex)
        printf '%X\n' $i > /tmp/drbl-virt_MAC
        Xen_MAC_6=$(cat /tmp/drbl-virt_MAC)
        echo "00:16:3e:${Xen_MAC_1}${Xen_MAC_2}:${Xen_MAC_3}${Xen_MAC_4}:${Xen_MAC_5}${Xen_MAC_6}" >> /opt/drbl-virt/etc/macadr-VM-$eth.txt
    else
        printf '%X\n' $i > /tmp/drbl-virt_MAC
        Xen_MAC_5=$(cat /tmp/drbl-virt_MAC)
        echo "00:16:3e:${Xen_MAC_1}${Xen_MAC_2}:${Xen_MAC_3}${Xen_MAC_4}:${Xen_MAC_5}" >> /opt/drbl-virt/etc/macadr-VM-$eth.txt
    fi
done

# delete tmp file
rm /tmp/drbl-virt_MAC
}


#function add_VM_dhcpd_conf(){
## backup dhcpd.conf
#if [ -e /etc/dhcp3/dhcpd.conf ]; then
#cp -f /etc/dhcp3/dhcpd.conf /etc/dhcp3/dhcpd.conf.drbl-virt_bak
#fi
#subnet_lines=$(cat -n /etc/dhcp3/dhcpd.conf | grep $eth_network | awk '{print $1}')
#host_lines=$(cat -n /etc/dhcp3/dhcpd.conf | grep 'host ' | grep '{' | awk '{print $1}')
#
#for subnet_line in $subnet_lines
#do
#    host_lines cat -n /etc/dhcp3/dhcpd.conf | sed -n "$subnet_line,\$p" | grep 'host .* {' | awk '{print $1}'
#done
#}

function delete_duplicating_MAC(){
drbl_mac_file="/etc/drbl/macadr-$eth.txt"
# if macadr-ethX.txt.drbl-virt_bak already have, backup it 
# else cp default backup
if [ -e $drbl_mac_file.drbl-virt_bak ]; then
    cp $drbl_mac_file $drbl_mac_file.$(date +%Y-%m-%d-%H-%M-%S).drbl-virt_bak
    cp -f $drbl_mac_file.drbl-virt_bak $drbl_mac_file
else 
    cp $drbl_mac_file $drbl_mac_file.drbl-virt_bak
fi

    # Delete duplating VM MAC
    for vm_mac in $(echo $VM_MACs)
    do
        vm_mac_lines=$(cat -n $drbl_mac_file | grep $vm_mac | awk '{print $1}' )
        # no duplicated vlaue, doesn't do it
        if [ -n "$vm_mac_lines" ]; then
            vm_mac_count=$(echo $vm_mac_lines | wc -w)
            for (( i=1 ; i<=${vm_mac_count} ; i++ ))
            do
                del_line=$(echo $vm_mac_lines | cut -d " " -f${i})
                sed -i "${del_line}d" $drbl_mac_file
            done
        fi
    done
}  


# [create ssh key amd cpoy to client]
function drbl_sshkey(){
# The reasone we do not to use $HOME is that sudo will not change
# environmental variable $HOME, but it will change the $USER
# we need to know who is really running this after applying sudo.
# say, sudo echo "$HOME", it will show user's home, instead of root's home,
REALHOME=$(LC_ALL=C grep -Ew "^$USER" /etc/passwd | cut -d":" -f6)
drblroot="/tftpboot/nodes"

if [ ! -f $REALHOME/.ssh/id_rsa ]; then
  ssh-keygen -t rsa -q -f $REALHOME/.ssh/id_rsa -N ""
fi

# Put authorized_keys for the user. 2 cases:
# (1). It is root running drbl-doit.
# (2). It is normal user running drbl-doit.
# For root, we will NOT copy authorized_keys in server, since the root in the client should not share the same authorized_keys with that in server. We only put them in the client. (Note! Every client has its own root directory in $ihost/root/)
# For normal user, we let user can ssh login back to server and other machine without password (Note! This is NFS-based home, so we just have to copy id_rsa.pub as authorized_keys in user's home, then no matter which machine user logins, it will use this key).
if [ "$UID" = "0" ]; then
  # for root, copy id_rsa.pub as authorized_keys in clients.
  for ihost in $drblroot/*; do
    if [ -f "$REALHOME/.ssh/id_rsa.pub" ]; then
      mkdir -p $ihost/root/.ssh
      cp -af $REALHOME/.ssh/id_rsa.pub $ihost/root/.ssh/authorized_keys
    fi
  done
else
  if [ -f "$REALHOME/.ssh/id_rsa.pub" ]; then
    cp -af $REALHOME/.ssh/id_rsa.pub $REALHOME/.ssh/authorized_keys
  fi
fi

}


# [Creat drbl-virter user]
function creat_drbl-virter(){
useradd -m -s /bin/bash drbl-virter
}


# [Download tomcat and mv drbl-virt.wat to wepapps]                           
function install_tomcat_and_mv_drbl-virt(){
if [ ! -e $Work_Home/tomcat-7.0.2.tar.gz ]; then
wget http://drbl-virt.googlecode.com/files/tomcat-7.0.2.tar.gz -P $Work_Home
fi                         
tar zxvf $Work_Home/tomcat-7.0.2.tar.gz -C $Work_Home/
mv $Work_Home/drbl-virt.war $Work_Home/tomcat-7.0.2/webapps/
chown -R drbl-virter.drbl-virter $Work_Home/tomcat-7.0.2
su  drbl-virter -c "$Work_Home/tomcat-7.0.2/bin/startup.sh"
echo ""
echo "[Go to http://{server_IP}:8080/drbl-virt/ to check !]"
}
