#!/bin/bash
### BEGIN INIT INFO
# Provides:          invirt-xen-config
# Required-Start:    $local_fs $remote_fs
# Required-Stop:     $local_fs $remote_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Startup script for the Invirt Xen host
# Description:       
### END INIT INFO

PACKAGE=invirt-xen-config
NAME="$PACKAGE"
DESC="Invirt Xen host"
PARENTPACKAGE=xend
SYSVMS=(s_master s_remote s_console)
GEN_FILES=(/etc/xen/xend-config.sxp.invirt "${SYSVMS[@]/#//etc/xen/sysvms/}")

dpkg -s "$PACKAGE" >/dev/null 2>/dev/null || exit 0

. /lib/init/gen-files.sh
. /lib/init/std-init.sh

start_sysvm() {
    # Attempt to start a sysvm, but only if it's not running already
    # somewhere on the cluster
    
    VM="$1"
    LV="${VM}_hda"
    DISK="/dev/xenvg/$LV"
    
    # Don't bother trying to start the VM if it's already running
    if xm list "$VM" >/dev/null 2>&1; then
        return 1
    fi
    
    RET=1
    # To keep multiple hosts from trying to start a VM at the same
    # time, lock VM creation at startup-time with a lock LV, since LV
    # creation is atomic
    if lvcreate -L 1K -n "lock_${LV}" xenvg >/dev/null 2>&1; then
        # If we can disable the LV, then the VM isn't already running
        # somewhere else
        if lvchange -a n "$DISK" >/dev/null 2>&1; then
            lvchange -a y "$DISK" >/dev/null 2>&1
            
            [ "$VERBOSE" != no ] && log_daemon_msg "Starting sysvm $VM"
            xm create "sysvms/$VM" >/dev/null
            [ "$VERBOSE" != no ] && log_end_msg $?
            RET=0
        fi
        
        # Regardless of whether we could get the lock or not, the
        # lvchange -a n probably disabled the LV somewhere; be sure we
        # clean up
        lvchange -a y "$DISK" >/dev/null 2>&1
    
        # Cleanup the lock, regardless of whether we started the LV
        lvchange -a n "/dev/xenvg/lock_${LV}" >/dev/null 2>&1
        lvchange -a ey "/dev/xenvg/lock_${LV}" >/dev/null 2>&1
        lvremove -f "/dev/xenvg/lock_${LV}" >/dev/null 2>&1
    fi
    
    return $RET
}

do_startup() {
    gen_files
    
    for vm in "${SYSVMS[@]}"; do
        start_sysvm "$vm"
    done
    
    echo 1 >/proc/sys/net/ipv4/ip_forward
    for i in all default; do
        echo 1 >/proc/sys/net/ipv4/conf/$i/rp_filter
        echo 1 >/proc/sys/net/ipv4/conf/$i/proxy_arp
    done
    
    invoke-rc.d "$PARENTPACKAGE" "$1"
}

do_start() {
    do_startup "start"
}

do_reload() {
    do_startup "reload"
}

do_stop() {
    invoke-rc.d "$PARENTPACKAGE" stop
}

std_init "$1"
