#!/bin/sh

# author : Nicolas Chipaux <aegiap@gandi.net> for GANDI
# all rights reserved.

umask 022

[ -f /etc/gandi/plugins-lib ] && . /etc/gandi/plugins-lib || exit 1
load_config

fsdevice_create() {
    if [ ! -d /proc/xen ]; then
        return
    fi

    # We create xvda if not already present. Often done by udev operating system.
    device_name=/dev/xvda
    for idx in $(seq 1 2); do
        part_name="${device_name}${idx}"
        [ -e "${part_name}" ] || mknod "${part_name}" b 202 ${idx}
    done
}

config_file=/etc/hosts

if [ ! -e "$config_file" ]; then
    cat > "$config_file" << EOT
# The following lines are desirable for IPv4 capable hosts
127.0.0.1       localhost

# The following lines are desirable for IPv6 capable hosts
::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
ff02::3 ip6-allhosts
EOT
fi

# /etc/fstab
config_file=/etc/fstab
correct_root_device=xvda1

if [ ! -d /proc/xen ]; then
    correct_root_device=sda
fi

new_value=$(blkid -s UUID -o value "/dev/${correct_root_device}")
if [ -z "${new_value}" ]; then
    new_value="/dev/${correct_root_device}"
else
    new_value="UUID=${new_value}"
fi

if [ ! -e "$config_file" ]; then
    cat > "${config_file}" << EOT
$new_value  /          ext4    rw,noatime,errors=remount-ro  0 1
devpts      /dev/pts   devpts  defaults      0 0
none        /proc      proc    rw,nosuid,noexec  0 0"
EOT
else
    root_element=$(awk 'BEGIN { FS="[\t\s ]+" } { if ($2 == "/") { if ($1 !~ "^#" ) print $1 } }' \
                  "${config_file}")

    if ! echo "${root_element}" | \
       egrep -q "^(UUID=|LABEL=|${correct_root_device})"; then
        cp -f "$config_file" "${config_file}".ga-old-$(date +"%d%m%Y_%H%M")
        sed -i -e "s,${root_element},${new_value},g" "${config_file}"
    fi
fi

fsdevice_create

exit 0
