#! /bin/sh

service xapi stop
sed -i -e '/UUID/ d' /etc/xensource-inventory
rm -f /var/xapi/*db*
rm -f /etc/firstboot.d/state/*
rm -f /etc/firstboot.d/log/*

cat << EOF > /etc/init.d/fix-uuids
#! /bin/sh

# chkconfig: 2345 19 99
# description: Regenerate UUIDs if missing in inventory

. /etc/init.d/functions
. /etc/xensource-inventory

generate_uuid () {
    uuidname=\$1

    echo -n "."
    new_uuid=\$(uuidgen)
    echo "\$1=\$(uuidgen)" >> /etc/xensource-inventory
}

start () {
    echo -n $"Fixing missing UUIDs: "

    [ -z "\$INSTALLATION_UUID" ] && generate_uuid INSTALLATION_UUID
    [ -z "\$CONTROL_DOMAIN_UUID" ] && generate_uuid CONTROL_DOMAIN_UUID

    success $"fixed UUIDs."
    echo
}

case "\$1" in
    start | restart)
        start
        ;;
    stop | status)
        ;;
    *)
        echo $"Usage: \$0 start"
        exit 1
        ;;
esac
EOF

chmod +x /etc/init.d/fix-uuids
chkconfig fix-uuids on

cat << EOF1 > /etc/init.d/fix-nw
#! /bin/sh

# chkconfig: 2345 19 99
# description: Fix up firstboot nw config for xapi firstboot

. /etc/init.d/functions
. /etc/xensource-inventory

find_mac() {
    dev=\$1

    echo "\$(ip addr show dev eth0|grep ether|cut -d ' ' -f 6)"
}

start () {
    echo -n \$"Fixing NW data for firstboot scripts "

    # only do all this if necessary?
    eth0_mac="\$(find_mac eth0)"

    rm -f /etc/firstboot.d/data/network.conf
    cat << EOF > /etc/firstboot.d/data/network.conf
ADMIN_INTERFACE=\$eth0_mac
INTERFACES=\$eth0_mac
EOF

    rm -f /etc/firstboot.d/data/interface-*.conf
    cat << EOF > /etc/firstboot.d/data/interface-\${eth0_mac}.conf
LABEL=eth0
MODE=dhcp
EOF

    success \$"fixed NW data"
    echo
}

case "\$1" in
    start | restart)
        start
        ;;
    stop | status)
        ;;
    *)
        echo \$"Usage: \$0 start"
        exit 1
        ;;
esac
EOF1

chmod +x /etc/init.d/fix-nw
chkconfig fix-nw on
