#  Copyright (c) 2008, Oracle. All rights reserved
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, version 2.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

# This file only can be sourced. It cannot be run stand alone...

## Global variables #######################################################
# Configuration file, defalut is /etc/sysconfig/oraclevm-template
CONF_FILE=${CONF_FILE:-/etc/sysconfig/oraclevm-template}

# log file, default is /var/log/oraclevm-template.log
LOG_FILE=${LOG_FILE:-/var/log/oraclevm-template.log}

# enable log, default is 1 - enabled.
ENABLE_LOG=${ENABLE_LOG:-1}

# Default timeout for interative question
DEFAULT_TIMEOUT=${DEFAULT_TIMEOUT:-30}

export PATH=/sbin:/bin:/usr/sbin:/usr/bin:$PATH

## functions for Amazon EC2 AMIs
ec2_random_root_password () {
    ovm_info "Generating random password for root user."
    echo $RANDOM | md5sum | cut -c 1-8 | \
    passwd --stdin root
}

ec2_update_ssh_publickey () {
    local PUB_KEY_URI=http://169.254.169.254/latest/meta-data/public-keys/0/openssh-key
    local PUB_KEY_FROM_HTTP=/tmp/openssh_id.pub
    local PUB_KEY_FROM_EPHEMERAL=/mnt/openssh_id.pub
    local ROOT_AUTHORIZED_KEYS=/root/.ssh/authorized_keys

    # We need somewhere to put the keys.
    if [ ! -d /root/.ssh ] ; then
            mkdir -p /root/.ssh
            chmod 700 /root/.ssh
    fi
    
    # Fetch credentials...
    ovm_info "-----CREDENTIALS RETRIEVAL-----"
    # First try http
    ovm_info "Attempting to retrieve public key from [$PUB_KEY_URI]"
    # --retry and familly options were added from curl 7.12.3
    if [[ $(rpm -q --qf "%{V}" curl) >  7.12.2 ]]; then
        curl --retry 3 --retry-delay 5 --silent --fail -o $PUB_KEY_FROM_HTTP $PUB_KEY_URI
    else
        if ! curl --silent --fail -o $PUB_KEY_FROM_HTTP $PUB_KEY_URI; then
            sleep 5
            if ! curl --silent --fail -o $PUB_KEY_FROM_HTTP $PUB_KEY_URI; then
                sleep 5
                curl --silent --fail -o $PUB_KEY_FROM_HTTP $PUB_KEY_URI
            fi
        fi
    fi
    if [ $? -eq 0 -a -e $PUB_KEY_FROM_HTTP ] ; then
        if [ ! -e $ROOT_AUTHORIZED_KEYS ] || ! grep -q -f $PUB_KEY_FROM_HTTP $ROOT_AUTHORIZED_KEYS
        then
            cat $PUB_KEY_FROM_HTTP >> $ROOT_AUTHORIZED_KEYS
            ovm_info "New key added to authrozied keys file from parameters"
        else
            ovm_info "Already have your key"
        fi
        rm -f $PUB_KEY_FROM_HTTP
    
    elif [ -e $PUB_KEY_FROM_EPHEMERAL ] ; then
        ovm_warn "Metadata fetch failed, trying from legacy ephemeral store location [$PUB_KEY_FROM_EPHEMERAL]"
        # Try back to ephemeral store if http failed.
        # NOTE: This usage is deprecated and will be removed in the future
        if [ ! -e $ROOT_AUTHORIZED_KEYS ] || ! grep -q -f $PUB_KEY_FROM_EPHEMERAL $ROOT_AUTHORIZED_KEYS
        then
            cat $PUB_KEY_FROM_EPHEMERAL >> $ROOT_AUTHORIZED_KEYS
            echo "New key added to authrozied keys file from ephemeral store"
        fi
        chmod 600 $PUB_KEY_FROM_EPHEMERAL
    
    fi
    
    if [ ! -f $ROOT_AUTHORIZED_KEYS ]
    then
        ovm_error "*!*!*! FATAL ERROR *!*!*! Unable to find authorized_keys file [$ROOT_AUTHORIZED_KEYS]"
    else
        ovm_info "Setting permissions on $ROOT_AUTHORIZED_KEYS to 0600"
        chmod 600 $ROOT_AUTHORIZED_KEYS
    fi
}

#ec2_update_yum_repo () {
#
#    ovm_info "Updating yum repository configuration file."
#    local release=$(lsb_release -r -s)
#    release=${release%%.*}
#    local repo_url="http://public-yum.oracle.com/public-yum-el${release}.repo"
#    local repo_local="/etc/yum.repos.d/public-yum-el${release}"
#    # --retry and familly options were added from curl 7.12.3
#    if [[ $(rpm -q --qf "%{V}" curl) >  7.12.2 ]]; then
#        curl --retry 3 --retry-delay 5 --silent --fail -o $repo_local $repo_url
#    else
#        if ! curl --silent --fail -o $repo_local $repo_url; then
#            sleep 5
#            if ! curl --silent --fail -o $repo_local $repo_url; then
#                sleep 5
#                curl --silent --fail -o $repo_local $repo_url
#            fi
#        fi
#    fi
#    if [ $? -ne 0 ]; then
#        ovm_warn "Failed to update yum repository configuration file from http://public-yum.oracle.com"
#        return 1
#    fi
#}

## internal functions #####################################################
# source a config file
# params:
# $1 - config file, if $1 is null, will load $CONF_FILE
function ovm_load_config
{
    local cfg
    if [ -n "$1" ]; then
        cfg=$1
    else
        cfg=$CONF_FILE
    fi
    [ ! -r "$cfg" ] && return 1
    ovm_log "Loading parameters from config file: $cfg"
    #eval $(cat $1 | sed -e '/^#/d;/^$/d;/^[[:space:]]*$/d;s/[[:space:]]//g')
    . $cfg
    ovm_debug $cfg:
    ovm_debug "$(cat $cfg|grep -v '^#')"
}

# mount product disk
# $1 - mount point
function ovm_mount_product_disk
{
    local p
    local mp=$1

    if egrep -q "hdb1|xvdb1" /proc/mounts; then
        mp=$(egrep "hdb1|xvdb1" /proc/mounts|awk '{print $2}')
        ovm_debug "already mounted on $mp"
        # set global variable TEMPLATE_MOUNT_POINT
        TEMPLATE_MOUNT_POINT=$mp
        return 0
    else
        [ -z "$mp" ] && return 1
        mkdir -p $mp
        for p in hdb1 xvdb1; do
            # only support ext3 filesystem here
            if grep -q "$p" /proc/partitions && \
               mount -t ext3 "/dev/$p" $mp >/dev/null 2>&1; then
                ovm_info "Mount /dev/$p on $mp"
                if ! grep -q "$mp" /etc/fstab; then
                    echo "/dev/$p	$mp	ext3	defaults 0 0" >>/etc/fstab
                fi
                return 0
           fi
       done
       return 1
    fi
}

# os cleanup
function ovm_cleanup_os
{
    local old_enable_log=$ENABLE_LOG
    # cleanup oraclevm-template log fist
    [ -e /var/log/oraclevm-template.log ] && \
        cat /dev/null > /var/log/oraclevm-template.log
    ovm_info "Starting OS cleanup at $(date)"
    if [ "$AMAZON_EC2_AMI" = YES -o "$AMAZON_EC2_AMI" = yes ]; then
        :
    else
        ovm_info "Resetting network configuration to DHCP."
        # reset as dhcp
        # disable logging temparorily here
        [ "$old_enable_log" = 1 ] && ENABLE_LOG=0
        ovm_configure_network dhcp localhost.localdomain >/dev/null
        # set  ENABLE_LOG back
        ENABLE_LOG=$old_enable_log
        # stop network
        ovm_info "Stopping network."
        service network stop
    fi
    # cleanup resolv.conf
    cat /dev/null >/etc/resolv.conf
    /bin/rm -f /etc/resolv.conf.*
    /bin/rm -f /var/lib/dhclient/dhclient-eth?.leases
    /bin/rm -f /var/lib/dhcp/dhclient-eth?.leases
    # remove mac address
    for f in /etc/sysconfig/network-scripts/ifcfg-eth*; do
        [ -e "$f" ] && sed -i '/^HWADDR=/d' $f
    done
    ovm_info "Cleaning up logs."
    # cleanup system logs
    [ -e /var/log/acpid ] && cat /dev/null > /var/log/acpid
    /bin/rm -f /var/log/messages.*
    [ -e /var/log/messages ] && cat /dev/null > /var/log/messages
    [ -e /var/log/secure ] && cat /dev/null > /var/log/secure
    [ -e /var/log/wtmp ] && cat /dev/null > /var/log/wtmp
    [ -e /var/log/faillog ] && cat /dev/null > /var/log/faillog
    [ -e /var/log/lastlog ] && cat /dev/null > /var/log/lastlog
    [ -e /var/log/yum.log ] && cat /dev/null > /var/log/yum.log
    [ -e /var/log/up2date ] && cat /dev/null > /var/log/up2date
    [ -e /var/log/anaconda.log ] && cat /dev/null > /var/log/anaconda.log
    /bin/rm -f /var/log/audit/audit.log.*
    [ -e /var/log/audit/audit.log ] && cat /dev/null > /var/log/audit/audit.log
    /bin/rm -f /root/install.log \
               /root/install.log.syslog \
               /root/anaconda-ks.cfg
    # remove update registration
    /bin/rm -f /etc/sysconfig/rhn/systemid
    # cleanup cache files
    ovm_info "Cleaning up cache files."
    [ -d /var/spool/up2date ] && \
        find /var/spool/up2date -type f -print0 | xargs -0 /bin/rm -f
    [ -d /var/cache/yum ] && /bin/rm -fr /var/cache/yum/*
    # cleanup ssh cache files
    [ -d /root/.ssh ] && /bin/rm -fr /root/.ssh
    # cleanup vnc cache files
    if [ -d /root/.vnc ]; then
        /bin/rm -f /root/.vnc/*.log
        /bin/rm -f /root/.vnc/passwd
    fi
    # cleanup bash history
    ovm_info "Cleaning up bash history."
    [ -e  /root/.bash_history ] && cat /dev/null > /root/.bash_history
    echo "Please run 'history -c' to clear current bash history."
    # cleanup root password info
    passwd -d root
    ovm_info "OS cleanup done."
    return 0
}

# OS mandatory reconfiguration includes:
# - regenerate ssh host keys if ssh server is installed
# - regenerate up2date uuid if up2date is installed
# [removed from 1.1.0-3]: rerun oracle-validated if oracle-validated is installed
function ovm_reconfigure_os
{
    ovm_log "Reconfiguring OS"
    # ssh host key
    if rpm -q openssh-server >/dev/null 2>&1; then
        ovm_info "Regenerating SSH host keys."
        /bin/rm -f /etc/ssh/ssh_host_*
        [ -x /etc/init.d/sshd ] && /etc/init.d/sshd restart
    fi
    # ec2 specific config
    if [ "$AMAZON_EC2_AMI" = YES -o "$AMAZON_EC2_AMI" = yes ]; then
        ec2_update_ssh_publickey
        ec2_random_root_password
        #ec2_update_yum_repo
    fi
    # up2date uuid
    if rpm -q up2date >/dev/null 2>&1; then
        ovm_info "Regenerating up2date UUID."
        cat > /etc/sysconfig/rhn/up2date-uuid <<-EOF
uuid[comment]=Universally Unique ID for this server
rhnuuid=$(/usr/bin/uuidgen)
EOF
    fi
    # we don't re-run oracle-validated during firstboot.
    # rerun oracle-validated-verify if oracle-validated is installed
    #if rpm -q oracle-validated >/dev/null 2>&1; then
    #    if [ -x /usr/bin/oracle-validated-verify ]; then
    #      ovm_info "Setting Oracle validated configuration parameters."
    #      /usr/bin/oracle-validated-verify 2> /dev/null 1>&2
    #    fi
    #fi
    return 0
}


# load(source) configuration file
function ovm_load_config
{
    [ ! -r "$1" ] && return 1
    ovm_log "Loading parameters from config file: $1"
    #eval $(cat $1 | sed -e '/^#/d;/^$/d;/^[[:space:]]*$/d;s/[[:space:]]//g')
    . $1
    ovm_debug $1:
    ovm_debug "$(cat $1|grep -v '^#')"
}


# display and log message
function ovm_msg
{
   local ret=$?
   local mode=$1
   shift
   [ -z "$*" ] && return $ret
   case "$mode" in
       0|LOGONLY)
         [ "$DEBUG" = 1 ] && echo "[LOG] ${0##*/}: $*"
         [ "$ENABLE_LOG" = 1 ] && [ -n "$LOG_FILE" ] && \
             echo "[LOG]  $(date +'%b %d %H:%M:%S') ${0##*/}: $*" >>  $LOG_FILE
         ;;
       1|INFO)
         [ "$DEBUG" = 1 ] && echo "[INFO] ${0##*/} :$*" || echo "$*"
         [ "$ENABLE_LOG" = 1 ] && [ -n "$LOG_FILE" ] && \
             echo "[INFO] $(date +'%b %d %H:%M:%S') ${0##*/}: $*" >>  $LOG_FILE
         ;;
       2|ERROR)
         [ "$DEBUG" = 1 ] && echo "[ERROR] ${0##*/} :$*" || echo "$*" >&2
         [ "$ENABLE_LOG" = 1 ] && [ -n "$LOG_FILE" ] && \
             echo "[ERROR] $(date +'%b %d %H:%M:%S') ${0##*/}: $*" >>  $LOG_FILE
         ;;
       3|WARNING)
         [ "$DEBUG" = 1 ] && echo "[WARN] ${0##*/} :$*" || echo "$*"
         [ "$ENABLE_LOG" = 1 ] && [ -n "$LOG_FILE" ] && \
             echo "[WARN] $(date +'%b %d %H:%M:%S') ${0##*/}: $*" >>  $LOG_FILE
         ;;
       4|DEBUG)
         [ "$DEBUG" = 1 ] && echo "[DEBUG] $*" && \
         [ "$ENABLE_LOG" = 1 ] && [ -n "$LOG_FILE" ] && \
             echo "[DEBUG] $(date +'%b %d %H:%M:%S') ${0##*/}: $*" >>  $LOG_FILE
         ;;
       *) ;;
   esac
   return $ret
}

## Public functions that product template reconfiguration script can use######

# Display normal infomation message to stdout and log file in log format
function ovm_info
{
    ovm_msg INFO "$*"
}

# Display error message to stderr and log file in log format
function ovm_error
{
    ovm_msg ERROR "$*"
}

# Display warnning message to stdout and log file in log format
function ovm_warn
{
    ovm_msg WARNING "$*"
}

# output to log file only in log format.
function ovm_log
{
    ovm_msg LOGONLY "$*"
}

# Display debug message only when variable DEBUG=1
function ovm_debug 
{
    ovm_msg DEBUG "$*"
}

# Disable firewall
function ovm_disable_firewall
{
    ovm_log "Disabling firewall"
    if [ -x /usr/bin/system-config-securitylevel-tui ]; then
        /usr/bin/system-config-securitylevel-tui -q --disabled
    else
        [ -x /sbin/iptables ] && /sbin/iptables -F
        [ -x /etc/init.d/iptables ] && /etc/init.d/iptables save
    fi
}

# Add a system user
# $1 - username
# $2 - password, if it's null, will prompt user to enter pasword
function ovm_add_user
{
    local username=$1
    local passwd=$2
    if [ -z "$username" ]; then
        ovm_error "** Username cannot be null."
        return 1
    fi
    if grep -q "^$username" /etc/passwd; then
        ovm_warn "Username already exists."
    else
        if useradd $username >/dev/null 2>&1; then
            ovm_info "Successfully added user '$username'."
        else
            ovm_error "** Failed to add user '$username'."
        fi
    fi
    ovm_set_password $username $passwd
}

# Set password
# $1 - username
# $2 - password, if it's null, will prompt user to enter pasword
function ovm_set_password
{
    local username=$1
    local passwd=$2
    local encpasswd
    if [ -z "$username" ] || ! id "$username" >/dev/null 2>&1; then
        ovm_error "Username cannot be null or does not exist."
        return 1
    fi
    if [ -n "$passwd" ]; then
        encpasswd=$(perl -e "print(crypt('$passwd','salt'),'\n')")
	usermod -p $encpasswd $username
    else
        while ! passwd $username; do
            :
        done
    fi
}

# Display "Press any key to continue", request user press keyboard
# default time out 30 seconds.
# $1 - timeout, timout=0 means wait forever untill user press a key.
function ovm_press_anykey
{
    local to=0
    [ -n "$1" ] && to=$1 || to=$DEFAULT_TIMEOUT
    echo
    stty -echo
    if [ $to -eq 0 ]; then
      read -n 1 -p "Press any key to continue..."
    else
      read -t $to -n 1 -p "Will continue in $to seconds, or press any key to continue..."
    fi
    echo
    stty echo
}

# Display "Press any key to continue", request user press keyboard
function press_anykey
{
    ovm_press_anykey 0
}

# function ovm_configure_network
# Usage:
# 1. interactive mode
#  A. No argument specified. -  prompt user to select using DHCP or not.
#  B. $1 = "static" - force to configure static ip address.
#                     prompt user to enter ipaddress, netmask, gateway,
#                                          dns, hostname
# 2. silent mode
#  A. $1 = "dhcp", force to configure dhcp silently.
#  B. force to configure dhcp and set hostname silently.
#     $1 = "dhcp"
#     $2 = hostname
#  C. 5 arguments are required to configure static ip address silently.
#     $1 - ip address
#     $2 - netmask
#     $3 - gateway
#     $4 - dns server IP
#     $5 - hostname
# Examples:
# - full interactive mode, no argument needs to be specified.
#   ovm_configure_network
# - Configure DHCP directly,
#   ovm_configure_network "dhcp"
# - Configure DHCP and set hostname
#   ovm_configure_network "dhcp" "myhost.mydomain.com"
# - Configure static IP directly but require user input for ip, hostname etc.
#   ovm_configure_network "static"
# - Configure static IP with ip/hostname etc. specified
#   ovm_configure_network "192.168.1.100" \
#                         "255.255.255.0" \
#                         "192.168.1.1" \
#                         "192.168.8.88" \
#                         "myhost.mydomain.com"
# 
function ovm_configure_network
{
  local usedhcp=255
  local device=eth0
  local ipaddr netmask hostname gateway hostname hwaddr n
  local sethostname=0

  # IPv4 IP address must be "a.b.c.d" where a, b, c and d are decimal
  # numbers between 0 and 255."
  local ip_regex="^([0-9]|[1-9][0-9]|1[0-9][0-9]|2([0-4][0-9]|5[0-5]))(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2([0-4][0-9]|5[0-5]))){3}$"
  # RFCs mandate that a hostname's labels may contain only the ASCII letters
  # 'a' through 'z' (case-insensitive), the digits '0' through '9', and the hyphen.
  # Hostname labels cannot begin or end with a hyphen. Each label/part has maximum
  # of 63 characters, last label/part should has 2-6 characters.
  local hostname_regex="^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,6}$"

  ovm_debug "args: $*"

  [ -r /etc/sysconfig/network-scripts/network-functions ] && \
    . /etc/sysconfig/network-scripts/network-functions

  hwaddr=$(get_hwaddr $device)

  echo
  ovm_info "Configuring network interface."
  # check device
  if ! ifconfig $device > /dev/null 2>&1; then
    ovm_error "** Device $device does not exist."
    return 1
  fi
  ovm_info "  Network device: $device"
  ovm_info "  Hardware address: $hwaddr"
  # if no args specified, prompt for dhcp or not
  if [ $# -eq 0 ]; then
    echo
    while true; do
    ##### prompt for using DHCP or not###
      echo -n "Do you want to enable dynamic IP configuration (DHCP) (Y|n)? " && \
          read -t $DEFAULT_TIMEOUT n
      case "$n" in
        ""|y|Y|yes|Yes|YES)
          ovm_debug "Use DHCP"
          usedhcp=1; break;;
        n|N|no|No|NO)
          ovm_debug "Use static IP address"
          usedhcp=0; break;;
        *) continue;;
      esac
    done
  elif [ $# -eq 1 ]; then
    # if "dhcp" is specified.
    if [ "$1" = "dhcp" ]; then
      usedhcp=1
    elif [ "$1" = "static" ]; then
      usedhcp=0
    else
      # wrong args.
      ovm_error "** Invalid argument for network reconfig."
      return 1
    fi
  elif [ $# -eq 2 -a "$1" = dhcp ]; then
    usedhcp=1
    hostname=$2
  elif [ $# -eq 5 ]; then
    usedhcp=0
  else
    # wrong arg numbers.
    ovm_error "** Invalid argument numbers for network reconfig."
    return 1
  fi
  # if "static" is specified or user select not to use dhcp
  if [ $usedhcp -eq 0 ]; then
    if [ $# -eq 5 ]; then
    # ip/nm/gw/dns/hostname should be specified here
       # not validate the args here.
       ipaddr=$1
       netmask=$2
       gateway=$3
       dns=$4
       hostname=$5
    else
    # get static ip/gw/nm/dns/hostname from intput
      echo
      # prompt for static ip
       while true; do
         echo -n "Enter static IP address: " && read n
         [ -z "$n" ] && continue
         if [ "$n" = 127.0.0.1 ] || [[ ! "$n" =~ $ip_regex ]]; then
           echo "** Invalid IP address." && continue
         fi
         ipaddr=$n && break
       done
       # prompt for netmask
       netmask_default=$(ipcalc --netmask $ipaddr | sed -e 's/.*=//')
       if [ -n "$netmask_default" ]; then
         default=" [$netmask_default]"
       else
         default=
       fi
       while true; do
         echo -n "Enter netmask:$default " && read n
         if [ -z "$n" ]; then
           if [ -n "$netmask_default" ]; then
             netmask=$netmask_default && break
           else
             continue
           fi
         fi
         if [[ ! "$n" =~ $ip_regex ]]; then
           echo "** Invalid netmask." && continue
         fi
         netmask=$n && break
       done
       # prompt for gateway
       while true; do
         echo -n "Enter gateway: " && read n
         [ -z "$n" ] && continue
         if [[ ! "$n" =~ $ip_regex ]]; then
           echo "** Invalid gateway." && continue
         fi
         gateway=$n && break
       done
       #prompt for dns
       while true; do
         echo -n "Enter DNS server: " && read n
         [ -z "$n" ] && continue
         if [[ ! "$n" =~ $ip_regex ]]; then
           echo "** Invalid DNS server." && continue
         fi
         dns=$n && break
       done
    fi
  fi
  ovm_debug "usedhcp=$usedhcp hostname=$hostname ipaddr=$ipaddr netmask=$netmask gateway=$gateway dns=$dns"
  
  # stop network
  echo
  ovm_log "Stopping network..."
  service network stop

  # reset default /etc/hosts
  cat > /etc/hosts <<EOF
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
EOF
  # cleanup /etc/resolv.conf
  cat /dev/null > /etc/resolv.conf
  # remove gateway entry in /etc/sysconfig/network
  sed -i -e "/^GATEWAY=/d" /etc/sysconfig/network
  # reset hostname
  set_hostname "localhost.localdomain"
  export HOSTNAME=$(hostname)

  echo
  ovm_info "Configuring network settings."
  #configure using DHCP
  if [ $usedhcp -eq 1 ]; then
    ovm_info "  IP configuration: DHCP"
    # write to and ifcfg-<deviceID>
    cat > /etc/sysconfig/network-scripts/ifcfg-$device <<-EOF
# generated by $0
DEVICE=$device
ONBOOT=yes
BOOTPROTO=dhcp
TYPE=Ethernet
EOF
    # reset hostname in /etc/sysconfig/network
    sed -i -e "s/^HOSTNAME=.*/HOSTNAME=localhost.localdomain/g" /etc/sysconfig/network

  # configure using static ip
  elif [ $usedhcp -eq 0 ]; then
    ovm_info "  IP configuration: Static IP address"
    # overwirte ifcf-<device>
    cat > /etc/sysconfig/network-scripts/ifcfg-$device <<-EOF
# generated by $0
DEVICE=$device
ONBOOT=yes
BOOTPROTO=static
IPADDR=$ipaddr
NETMASK=$netmask
GATEWAY=$gateway
TYPE=Ethernet
EOF
    # rewrite resolv.conf with new dns
    echo ";generated by $0" > /etc/resolv.conf
    echo "nameserver $dns" >> /etc/resolv.conf
  else
    return 1
  fi

  # start network
  echo
  ovm_log "Starting network..."
  service network start
  #check if ip address is valid
  if ! ifconfig $device 2>/dev/null | grep -q "inet addr" ; then
    ovm_error "** Could not get a valid IP address."
    return 2
  fi

  if [ $usedhcp -eq 1 ]; then
    if [ $# -eq 2 ]; then
      ovm_debug "Set hostname to $hostname"
      sethostname=1
    else
    echo
    while true; do
      ##### prompt set hostname or not
      echo -n "Do you want to manually configure the hostname (y|N)? " \
          && read -t $DEFAULT_TIMEOUT n
      case "$n" in
        y|Y|yes|Yes|YES)
          ovm_debug "Set hostname"
          sethostname=1; break;;
        ""|n|N|no|No|NO)
          ovm_debug "Not set hostname"
          sethostname=0; break;;
        *) continue;;
      esac
    done
    fi
  fi

  if [ $usedhcp -eq 0 ] || [ $usedhcp -eq 1 -a $sethostname -eq 1 ]; then
    if [ $# -ne 2 -a $# -ne 5 ]; then
    #prompt for hostname
    hostname_default=$(ipcalc --silent --hostname $ipaddr | sed -e 's/.*=//')
    if [ -n "$hostname_default" ]; then
      default=" [$hostname_default]"
    else
      default=
    fi
    echo
    while true; do
      echo -n "Enter hostname (e.g, host.example.com):$default " && read n
      [ "$n" = localhost.localdomain -o "$n" = localhost ] && continue
      if [ -z "$n" ]; then
        if [ -n "$hostname_default" ]; then
          hostname=$hostname_default && break
        else
          continue
        fi
      fi
      if [[ ! "$n" =~ $hostname_regex ]]; then
        echo "** Invalid hostname." && continue
      fi
      # host name can not be longer than 64 bytes
      if [ $(echo -n "$n"|wc -m) -gt 64 ]; then
        echo "** Hostname too long." && continue
      fi
      hostname=$n && break
    done
    fi
 
    # set hostname
    ovm_debug "set hostname $hostname"
    set_hostname $hostname
    export HOSTNAME=$(hostname)
    sed -i -e "s/^HOSTNAME=.*/HOSTNAME=$hostname/g" /etc/sysconfig/network

    if [ $usedhcp -eq 0 ]; then
      # rewrite resolv.conf with new dns
      sed -i '/^search/d' /etc/resolv.conf
      echo "search ${HOSTNAME#*.}" >> /etc/resolv.conf
    fi
    if [ $usedhcp -eq 1 ]; then
      ipaddr=$(ifconfig $device | grep "inet addr" | sed -e 's/.*inet addr:\([^ ]*\) .*/\1/')
    fi
    # add hostname ip alias to /etc/hosts
    if ! need_hostname; then
      ovm_log "add hostname ip alias to /etc/hosts"
      echo "$ipaddr	$HOSTNAME ${HOSTNAME%%.*}" >> /etc/hosts
      ovm_debug "$ipaddr $HOSTNAME ${HOSTNAME%%.*}"
    fi
  fi

  # export new hostname
  export HOSTNAME=$(hostname)

  ovm_debug "display cfg ifcfg-$device"
  ovm_debug "$(cat /etc/sysconfig/network-scripts/ifcfg-$device)"
  ovm_debug "display network"
  ovm_debug "$(cat /etc/sysconfig/network)"

  echo
  ovm_info "Network configuration changed successfully."
  if [ $usedhcp -eq 1 ]; then
    config="DHCP"
  else
    config="Static IP address"
  fi
  ipaddr=$(ifconfig $device | grep "inet addr" | sed -e 's/.*inet addr:\([^ ]*\) .*/\1/')
  netmask=$(ifconfig $device | grep "inet addr" | sed -e 's/.*Mask:\([^ ]*\)$/\1/')
  gateway=$(ip route | grep "default" | awk '{print $3}')
  dns=$(grep "nameserver" /etc/resolv.conf | head -1 | awk '{print $2}')
  ovm_info "  IP configuration: $config"
  ovm_info "  IP address:       $ipaddr"
  ovm_info "  Netmask:          $netmask" 
  ovm_info "  Gateway:          $gateway" 
  ovm_info "  DNS server:       $dns" 
  ovm_info "  Hostname:         $(hostname)" 
  return 0
} #end ovm_configure_network


