#!/bin/bash
#
# /etc/rc.d/rc.sysinit - run once at boot time
#
# Taken in part from Miquel van Smoorenburg's bcheckrc.
#

HOSTNAME=`/bin/hostname`
HOSTTYPE=`uname -m`
unamer=`uname -r`

set -m

if [ -f /etc/sysconfig/network ]; then
    . /etc/sysconfig/network
fi
if [ -z "$HOSTNAME" -o "$HOSTNAME" = "(none)" ]; then
    HOSTNAME=localhost
fi

if [ ! -e /proc/mounts ]; then 
    mount -n -t proc /proc /proc
    mount -n -t sysfs /sys /sys >/dev/null 2>&1
fi
if [ ! -d /proc/bus/usb ]; then
    modprobe usbcore >/dev/null 2>&1 && mount -n -t usbfs /proc/bus/usb /proc/bus/usb
else
    mount -n -t usbfs /proc/bus/usb /proc/bus/usb
fi
 
. /etc/init.d/functions

# Check SELinux status
selinuxfs="$(fstab_decode_str `LC_ALL=C awk '/ selinuxfs / { print $2 }' /proc/mounts`)"
SELINUX_STATE=
if [ -n "$selinuxfs" ] && [ "`cat /proc/self/attr/current`" != "kernel" ]; then
    if [ -r "$selinuxfs/enforce" ] ; then
        SELINUX_STATE=`cat "$selinuxfs/enforce"`
    else
        # assume enforcing if you can't read it
        SELINUX_STATE=1
    fi
fi

if [ -n "$SELINUX_STATE" -a -x /sbin/restorecon ] && LC_ALL=C fgrep -q " /dev " /proc/mounts ; then
    /sbin/restorecon  -R /dev 2>/dev/null
fi

disable_selinux() {
    echo $"*** Warning -- SELinux is active"
    echo $"*** Disabling security enforcement for system recovery."
    echo $"*** Run 'setenforce 1' to reenable."
    echo "0" > "$selinuxfs/enforce"
}

relabel_selinux() {
    if [ -x /usr/bin/rhgb-client ] && /usr/bin/rhgb-client --ping ; then
    chvt 1
    fi
    # if /sbin/init is not labeled correctly this process is running in the 
    # wrong context, so a reboot will be reuired after relabel
    REBOOTFLAG=`restorecon -v /sbin/init`
    AUTORELABEL=
    . /etc/selinux/config
    if [ "$AUTORELABEL" = "0" ]; then
     rm -f  /.autorelabel 

     echo
    echo $"*** Warning -- SELinux ${SELINUXTYPE} policy relabel is required. "
     echo $"*** /etc/selinux/config indicates you want to manually fix labeling"
     echo $"*** problems. Dropping you to a shell; the system will reboot"
     echo $"*** when you leave the shell."
     echo "0" > $selinuxfs/enforce
     sulogin
 
     echo $"Unmounting file systems"
     umount -a
     mount -n -o remount,ro /
     echo $"Automatic reboot in progress."
     reboot -f
    else
     echo
     echo $"*** Warning -- SELinux ${SELINUXTYPE} policy relabel is required."
     echo $"*** Relabeling could take a very long time, depending on file"
     echo $"*** system size and speed of hard drives."
 
     echo "0" > $selinuxfs/enforce
     /sbin/fixfiles restore > /dev/null 2>&1 
     rm -f  /.autorelabel 
     if [ ! -z "$REBOOTFLAG" ]; then 
         echo $"Automatic reboot in progress."
         reboot -f
     fi
     echo $SELINUX_STATE > $selinuxfs/enforce
     if [ -x /usr/bin/rhgb-client ] && /usr/bin/rhgb-client --ping ; then
         chvt 8
     fi
    fi
}

key_is_random() {
    [ "$1" = "/dev/urandom" -o "$1" = "/dev/hw_random" \
    -o "$1" = "/dev/random" ]
}

# Because of a chicken/egg problem, init_crypto must be run twice.  /var may be
# encrypted but /var/lib/random-seed is needed to initialize swap.
init_crypto() {
    local have_random dst src key opt mode owner params makeswap skip arg opt
    local param value rc ret mke2fs mdir

    ret=0
    have_random=$1
    while read dst src key opt; do
    [ -z "$dst" -o "${dst#\#}" != "$dst" ] && continue
        [ -b "/dev/mapper/$dst" ] && continue;
    if [ "$have_random" = 0 ] && key_is_random "$key"; then
        continue
    fi
    if [ -n "$key" -a "x$key" != "xnone" ]; then
        if test -e "$key" ; then
        owner=$(ls -l $key | (read a b owner rest; echo $owner))
        if ! key_is_random "$key"; then
        mode=$(ls -l "$key" | cut -c 5-10)
            if [ "$mode" != "------" ]; then
               echo $"INSECURE MODE FOR $key"
            fi
        fi
        if [ "$owner" != root ]; then
            echo $"INSECURE OWNER FOR $key"
        fi
        else
        echo $"Key file for $dst not found, skipping"
        ret=1
        continue
        fi
    else
        key=""
    fi
    params=""
    makeswap=""
    mke2fs=""
    skip=""
    # Parse the src field for UUID= and convert to real device names
    if [ "${src%%=*}" == "UUID" ]; then
        src=$(/sbin/blkid -t "$src" -l -o device)
    elif [ "${src/^\/dev\/disk\/by-uuid\/}" != "$src" ]; then
        src=$(__readlink $src)
    fi
    # Parse the options field, convert to cryptsetup parameters
    # and contruct the command line
    while [ -n "$opt" ]; do
        arg=${opt%%,*}
        opt=${opt##$arg}
        opt=${opt##,}
        param=${arg%%=*}
        value=${arg##$param=}

        case "$param" in
        cipher)
        params="$params -c $value"
        if [ -z "$value" ]; then
            echo $"$dst: no value for cipher option, skipping"
            skip="yes"
        fi
        ;;
        size)
        params="$params -s $value"
        if [ -z "$value" ]; then
            echo $"$dst: no value for size option, skipping"
            skip="yes"
        fi
        ;;
        hash)
        params="$params -h $value"
        if [ -z "$value" ]; then
            echo $"$dst: no value for hash option, skipping"
            skip="yes"
        fi
        ;;
        verify)
            params="$params -y"
        ;;
        swap)
        makeswap=yes
        ;;
        tmp)
        mke2fs=yes
        esac
    done
    if [ "$skip" = "yes" ]; then
        ret=1
        continue
    fi
    if [ -z "$key" -a -x /usr/bin/rhgb-client ] \
        && /usr/bin/rhgb-client --ping ; then
        chvt 1
    fi
    if cryptsetup isLuks "$src" 2>/dev/null; then
        if key_is_random "$key"; then
        echo $"$dst: LUKS requires non-random key, skipping"
        ret=1
        continue
        fi
        if [ -n "$params" ]; then
        echo "$dst: options are invalid for LUKS partitions," \
            "ignoring them"
        fi
        /sbin/cryptsetup ${key:+-d $key} luksOpen "$src" "$dst" <&1
    else
        /sbin/cryptsetup $params ${key:+-d $key} create "$dst" "$src" <&1
    fi
    rc=$?
    if [ -z "$key" -a -x /usr/bin/rhgb-client ] \
        && /usr/bin/rhgb-client --ping ; then
        chvt 8
    fi
    if [ $rc -ne 0 ]; then
        ret=1
        continue
    fi
    if [ -b "/dev/mapper/$dst" ]; then
        if [ "$makeswap" = "yes" ]; then
        mkswap "/dev/mapper/$dst" 2>/dev/null >/dev/null
        fi
        if [ "$mke2fs" = "yes" ]; then
        if mke2fs "/dev/mapper/$dst" 2>/dev/null >/dev/null \
            && mdir=$(mktemp -d /tmp/mountXXXXXX); then
            mount "/dev/mapper/$dst" "$mdir" && chmod 1777 "$mdir"
            umount "$mdir"
            rmdir "$mdir"
        fi
        fi
    fi
    done < /etc/crypttab
    return $ret
}

if [ -x /sbin/setsysfont -a -c /dev/tty1 ]; then
   /sbin/setsysfont < /dev/tty1 > /dev/tty1 2>/dev/null
fi

# Print a text banner.
echo -en $"\t\tWelcome to "
read -r redhat_release < /etc/redhat-release
if [[ "$redhat_release" =~ "Red Hat" ]]; then
 [ "$BOOTUP" = "color" ] && echo -en "\\033[0;31m"
 echo -en "Red Hat"
 [ "$BOOTUP" = "color" ] && echo -en "\\033[0;39m"
 PRODUCT=`sed "s/Red Hat \(.*\) release.*/\1/" /etc/redhat-release`
 echo " $PRODUCT"
elif [[ "$redhat_release" =~ "Fedora" ]]; then
 [ "$BOOTUP" = "color" ] && echo -en "\\033[0;34m"
 echo -en "Fedora"
 [ "$BOOTUP" = "color" ] && echo -en "\\033[0;39m"
 PRODUCT=`sed "s/Fedora \(.*\) release.*/\1/" /etc/redhat-release`
 echo " $PRODUCT"
elif [[ "$redhat_release" =~ "CentOS" ]]; then
 [ "$BOOTUP" = "color" ] && echo -en "\\033[0;36m"
 PRODUCT=`sed "s/CentOS \(.*\) release.*/\1/" /etc/redhat-release`
 echo -e " $PRODUCT"
 [ "$BOOTUP" = "color" ] && echo -en "\\033[0;39m"
else
 PRODUCT=`sed "s/ release.*//g" /etc/redhat-release`
 echo "$PRODUCT"
fi
if [ "$PROMPT" != "no" ]; then
 echo -en $"\t\tPress 'I' to enter interactive startup."
 echo
fi

# Set the system clock.
update_boot_stage RCclock
ARC=0
SRM=0
UTC=0

if [ -f /etc/sysconfig/clock ]; then
   . /etc/sysconfig/clock

   # convert old style clock config to new values
   if [ "${CLOCKMODE}" = "GMT" ]; then
      UTC=true
   elif [ "${CLOCKMODE}" = "ARC" ]; then
      ARC=true
   fi
fi

CLOCKDEF=""
CLOCKFLAGS="$CLOCKFLAGS --hctosys"

case "$UTC" in
    yes|true)    CLOCKFLAGS="$CLOCKFLAGS --utc"
        CLOCKDEF="$CLOCKDEF (utc)" ;;
    no|false)    CLOCKFLAGS="$CLOCKFLAGS --localtime"
        CLOCKDEF="$CLOCKDEF (localtime)" ;;
esac
case "$ARC" in
    yes|true)    CLOCKFLAGS="$CLOCKFLAGS --arc"
        CLOCKDEF="$CLOCKDEF (arc)" ;;
esac
case "$SRM" in
    yes|true)    CLOCKFLAGS="$CLOCKFLAGS --srm"
        CLOCKDEF="$CLOCKDEF (srm)" ;;
esac

[ -x /sbin/hwclock ] && /sbin/hwclock $CLOCKFLAGS

action $"Setting clock $CLOCKDEF: `date`" /bin/true

# Fix console loglevel
if [ -n "$LOGLEVEL" ]; then
    /bin/dmesg -n $LOGLEVEL
fi


# Only read this once.
cmdline=$(cat /proc/cmdline)

# Initialize hardware
if [ -f /proc/sys/kernel/modprobe ]; then
   if ! strstr "$cmdline" nomodules && [ -f /proc/modules ] ; then
       sysctl -w kernel.modprobe="/sbin/modprobe" >/dev/null 2>&1
   else
       # We used to set this to NULL, but that causes 'failed to exec' messages"
       sysctl -w kernel.modprobe="/bin/true" >/dev/null 2>&1
   fi
fi

touch /dev/.in_sysinit >/dev/null 2>&1

# Set default affinity
if [ -x /bin/taskset ]; then
   if strstr "$cmdline" default_affinity= ; then
     for arg in $cmdline ; do
         if [ "${arg##default_affinity=}" != "${arg}" ]; then
             /bin/taskset -p ${arg##default_affinity=} 1
         fi
     done
   fi
fi

nashpid=$(pidof nash 2>/dev/null)
[ -n "$nashpid" ] && kill $nashpid >/dev/null 2>&1
unset nashpid
/sbin/start_udev

# Load other user-defined modules
for file in /etc/sysconfig/modules/*.modules ; do
  [ -x $file ] && $file
done

# Load modules (for backward compatibility with VARs)
if [ -f /etc/rc.modules ]; then
    /etc/rc.modules
fi

# Start the graphical boot, if necessary; /usr may not be mounted yet, so we
# may have to do this again after mounting
RHGB_STARTED=0
mount -n /dev/pts >/dev/null 2>&1
[ -n "$SELINUX_STATE" ] && restorecon /dev/pts >/dev/null 2>&1

if strstr "$cmdline" rhgb && ! strstr "$cmdline" early-login && [ "$BOOTUP" = "color" -a "$GRAPHICAL" = "yes" -a -x /usr/bin/rhgb ]; then
   ( . /etc/sysconfig/i18n 2>/dev/null ; /usr/bin/rhgb )
   RHGB_STARTED=1
fi

# Configure kernel parameters
update_boot_stage RCkernelparam
sysctl -e -p /etc/sysctl.conf >/dev/null 2>&1

if [ -x /bin/loadkeys ]; then
 KEYTABLE=
 KEYMAP=
 if [ -f /etc/sysconfig/console/default.kmap ]; then
  KEYMAP=/etc/sysconfig/console/default.kmap
 else
  if [ -f /etc/sysconfig/keyboard ]; then
    . /etc/sysconfig/keyboard
  fi
  if [ -n "$KEYTABLE" -a -d "/lib/kbd/keymaps" ]; then
     KEYMAP="$KEYTABLE.map"
  fi
 fi
 if [ -n "$KEYMAP" ]; then 
  if [ -n "$KEYTABLE" ]; then
    echo -n $"Loading default keymap ($KEYTABLE): "
  else
    echo -n $"Loading default keymap: "
  fi
  LOADKEYS=loadkeys
  if [ "${LANG}" != "${LANG%%.UTF-8}" -o "${LANG}" != "${LANG%%.utf8}" ]; then
      LOADKEYS="loadkeys -u"
  fi
  $LOADKEYS $KEYMAP < /dev/tty0 > /dev/tty0 2>/dev/null && \
     success $"Loading default keymap" || failure $"Loading default keymap"
  echo
 fi
fi

# Set the hostname.
update_boot_stage RChostname
action $"Setting hostname ${HOSTNAME}: " hostname ${HOSTNAME}

# Initialize ACPI bits
if [ -d /proc/acpi ]; then
    for module in /lib/modules/$unamer/kernel/drivers/acpi/* ; do
        module=${module##*/}
        module=${module%.ko}
        modprobe $module >/dev/null 2>&1
    done
fi

# RAID setup
update_boot_stage RCraid
[ -x /sbin/nash ] && echo "raidautorun /dev/md0" | nash --quiet
if [ -f /etc/mdadm.conf ]; then
    /sbin/mdadm -A -s
fi

# Device mapper & related initialization
if ! LC_ALL=C fgrep -q "device-mapper" /proc/devices 2>/dev/null ; then
    modprobe dm-mod >/dev/null 2>&1
fi
mkdir -p /dev/mapper >/dev/null 2>&1
mknod /dev/mapper/control c \
    $(awk '/ misc$/ { print $1 }' /proc/devices) \
    $(awk '/ device-mapper$/ { print $1 }' /proc/misc) >/dev/null 2>&1
[ -n "$SELINUX_STATE" ] && restorecon /dev/mapper /dev/mapper/control >/dev/null 2>&1

if [ -f /etc/crypttab ]; then
    s=$"Starting disk encryption:"
    echo "$s"
    init_crypto 0 && success "$s" || failure "$s"
    echo
fi

if [ -c /dev/mapper/control ]; then
        if ! strstr "$cmdline" nompath && [ -f /etc/multipath.conf -a \
            -x /sbin/multipath.static ]; then
        modprobe dm-multipath > /dev/null 2>&1
        /sbin/multipath.static -v 0
        if [ -x /sbin/kpartx ]; then
            /sbin/dmsetup ls --target multipath --exec "/sbin/kpartx -a -p p"
        fi
    fi
    
    if ! strstr "$cmdline" nodmraid && [ -x /sbin/dmraid.static ]; then
        modprobe dm-mirror >/dev/null 2>&1
        for x in $(/sbin/dmraid.static -ay -i -p -t 2>/dev/null | \
                egrep -iv "^no " | \
                awk -F ':' '{ print $1 }') ; do
            dmname=$(resolve_dm_name $x)
            [ -z "$dmname" ] && continue
            /sbin/dmraid.static -ay -i -p "$dmname" >/dev/null 2>&1
            /sbin/kpartx -a -p p "/dev/mapper/$dmname"
        done
    fi
    
    if [ -x /sbin/lvm.static ]; then
        action $"Setting up Logical Volume Management:" /sbin/lvm.static vgchange -a y --ignorelockingfailure
    fi
fi

if [ -f /etc/crypttab ]; then
    s=$"Starting disk encryption:"
    echo "$s"
    init_crypto 0 && success "$s" || failure "$s"
    echo
fi

if [ -f /fastboot ] || strstr "$cmdline" fastboot ; then
    fastboot=yes
fi

if [ -f /fsckoptions ]; then
    fsckoptions=`cat /fsckoptions`
fi

if [ -f /forcefsck ] || strstr "$cmdline" forcefsck ; then
    fsckoptions="-f $fsckoptions"
elif [ -f /.autofsck ]; then
    [ -f /etc/sysconfig/autofsck ] && . /etc/sysconfig/autofsck
    if [ "$AUTOFSCK_DEF_CHECK" = "yes" ]; then
        AUTOFSCK_OPT="$AUTOFSCK_OPT -f"
    fi
    if [ -n "$AUTOFSCK_SINGLEUSER" ]; then
        echo
        echo $"*** Warning -- the system did not shut down cleanly. "
        echo $"*** Dropping you to a shell; the system will continue"
        echo $"*** when you leave the shell."
        [ -n "$SELINUX_STATE" ] && echo "0" > $selinuxfs/enforce
        sulogin
        [ -n "$SELINUX_STATE" ] && echo "1" > $selinuxfs/enforce
    fi
    fsckoptions="$AUTOFSCK_OPT $fsckoptions"
fi

if [ "$BOOTUP" = "color" ]; then
    fsckoptions="-C $fsckoptions"
else
    fsckoptions="-V $fsckoptions"
fi

READONLY=
if [ -f /etc/sysconfig/readonly-root ]; then
    . /etc/sysconfig/readonly-root
fi
if strstr "$cmdline" readonlyroot ; then
    READONLY=yes
    [ -z "$RW_MOUNT" ] && RW_MOUNT=/var/lib/stateless/writable
fi
if strstr "$cmdline" noreadonlyroot ; then
    READONLY=no
fi

if [ "$READONLY" = "yes" -o "$TEMPORARY_STATE" = "yes" ]; then

    mount_empty() {
        if [ -e "$1" ]; then
            echo "$1" | cpio -p -vd "$RW_MOUNT" &>/dev/null
            mount -n --bind "$RW_MOUNT$1" "$1"
        fi
    }

    mount_dirs() {
        if [ -e "$1" ]; then
            mkdir -p "$RW_MOUNT$1"
            # fixme: find is bad
            find "$1" -type d -print0 | cpio -p -0vd "$RW_MOUNT" &>/dev/null
            mount -n --bind "$RW_MOUNT$1" "$1"
        fi
    }

    mount_files() {
        if [ -e "$1" ]; then
            cp -a --parents "$1" "$RW_MOUNT"
            mount -n --bind "$RW_MOUNT$1" "$1"
        fi
    }

    # Common mount options for scratch space regardless of 
    # type of backing store
    mountopts=

    # Scan partitions for local scratch storage
    rw_mount_dev=$(blkid -t LABEL="$RW_LABEL" -l -o device)

    # First try to mount scratch storage from /etc/fstab, then any
    # partition with the proper label.  If either succeeds, be sure
    # to wipe the scratch storage clean.  If both fail, then mount
    # scratch storage via tmpfs.
    if mount $mountopts "$RW_MOUNT" > /dev/null 2>&1 ; then
        rm -rf "$RW_MOUNT" > /dev/null 2>&1
    elif [ x$rw_mount_dev != x ] && mount $rw_mount_dev $mountopts "$RW_MOUNT" > /dev/null 2>&1; then
        rm -rf "$RW_MOUNT"  > /dev/null 2>&1
    else
        mount -n -t tmpfs $mountopts none "$RW_MOUNT"
    fi

    for file in /etc/rwtab /etc/rwtab.d/* ; do
        is_ignored_file "$file" && continue
            [ -f $file ] && cat $file | while read type path ; do
            case "$type" in
                empty)
                    mount_empty $path
                    ;;
                files)
                    mount_files $path
                    ;;
                dirs)
                    mount_dirs $path
                    ;;
                *)
                    ;;
            esac
            [ -n "$SELINUX_STATE" -a -e "$path" ] && restorecon -R "$path"
        done
    done

    # In theory there should be no more than one network interface active
    # this early in the boot process -- the one we're booting from.
    # Use the network address to set the hostname of the client.  This
    # must be done even if we have local storage.
    ipaddr=
    if [ "$HOSTNAME" = "localhost" -o "$HOSTNAME" = "localhost.localdomain" ]; then
        ipaddr=$(ip addr show to 0/0 scope global | awk '/[[:space:]]inet / { print gensub("/.*","","g",$2) }')
        if [ -n "$ipaddr" ]; then
            eval $(ipcalc -h $ipaddr 2>/dev/null)
            hostname ${HOSTNAME}
        fi
    fi
    
    # Clients with read-only root filesystems may be provided with a
    # place where they can place minimal amounts of persistent
    # state.  SSH keys or puppet certificates for example.
    #
    # Ideally we'll use puppet to manage the state directory and to
    # create the bind mounts.  However, until that's all ready this
    # is sufficient to build a working system.

    # First try to mount persistent data from /etc/fstab, then any
    # partition with the proper label, then fallback to NFS
    state_mount_dev=$(blkid -t LABEL="$STATE_LABEL" -l -o device)
    if mount $mountopts $STATE_OPTIONS "$STATE_MOUNT" > /dev/null 2>&1 ; then
        /bin/true
    elif [ x$state_mount_dev != x ] && mount $state_mount_dev $mountopts "$STATE_MOUNT" > /dev/null 2>&1;  then
        /bin/true
    elif [ ! -z "$CLIENTSTATE" ]; then
        # No local storage was found.  Make a final attempt to find 
        # state on an NFS server.

        mount -t nfs $CLIENTSTATE/$HOSTNAME $STATE_MOUNT -o rw,nolock
    fi

    if [ -d $STATE_MOUNT/etc ]; then
        # Copy the puppet CA's cert from the r/o image into the
        # state directory so that we can create a bind mount on
        # the ssl directory for storing the client cert.  I'd really
        # rather have a unionfs to deal with this stuff
        cp --parents -f -p /var/lib/puppet/ssl/certs/ca.pem $STATE_MOUNT 2>/dev/null

        # In the future this will be handled by puppet
        for i in $(grep -v "^#" $STATE_MOUNT/files); do
            if [ -e $i ]; then
                 mount -n -o bind $STATE_MOUNT/${i} ${i}
            fi
         done
    fi
fi
 
if ! [[ " $fsckoptions" =~ " -y" ]]; then
        fsckoptions="-a $fsckoptions"
fi

_RUN_QUOTACHECK=0
if [ -f /forcequotacheck ] || strstr "$cmdline" forcequotacheck ; then
    _RUN_QUOTACHECK=1
fi
if [ -z "$fastboot" -a "$READONLY" != "yes" ]; then

        STRING=$"Checking filesystems"
    echo $STRING
    if [ "${RHGB_STARTED}" != "0" -a -w /etc/rhgb/temp/rhgb-console ]; then
        fsck -T -t noopts=_netdev -A $fsckoptions > /etc/rhgb/temp/rhgb-console
    else
        fsck -T -t noopts=_netdev -A $fsckoptions
    fi
    rc=$?
    
    if [ "$rc" -eq "0" ]; then
        success "$STRING"
        echo
    elif [ "$rc" -eq "1" ]; then
            passed "$STRING"
        echo
    elif [ "$rc" -eq "2" -o "$rc" -eq "3" ]; then 
        echo $"Unmounting file systems"
        umount -a
        mount -n -o remount,ro /
        echo $"Automatic reboot in progress."
        reboot -f
        fi
    
        # A return of 4 or higher means there were serious problems.
    if [ $rc -gt 1 ]; then
            if [ -x /usr/bin/rhgb-client ] && /usr/bin/rhgb-client --ping ; then
            chvt 1
        fi

        failure "$STRING"
        echo
        echo
        echo $"*** An error occurred during the file system check."
        echo $"*** Dropping you to a shell; the system will reboot"
        echo $"*** when you leave the shell."

                str=$"(Repair filesystem)"
        PS1="$str \# # "; export PS1
        [ "$SELINUX_STATE" = "1" ] && disable_selinux
        sulogin

        echo $"Unmounting file systems"
        umount -a
        mount -n -o remount,ro /
        echo $"Automatic reboot in progress."
        reboot -f
    elif [ "$rc" -eq "1" ]; then
        _RUN_QUOTACHECK=1
    fi
    if [ -f /.autofsck -a -x /usr/bin/rhgb-client ] && /usr/bin/rhgb-client --ping ; then
        chvt 8
        fi
fi

# Update quotas if necessary
if [ X"$_RUN_QUOTACHECK" = X1 -a -x /sbin/quotacheck ]; then
    if [ -x /sbin/convertquota ]; then
        # try to convert old quotas
        for mountpt in `LC_ALL=C awk '$4 ~ /quota/{print $2}' /etc/mtab` ; do
            mountpt="$(fstab_decode_str "$mountpt")"
        if [ -f "$mountpt/quota.user" ]; then
            action $"Converting old user quota files: " \
            /sbin/convertquota -u "$mountpt" && \
            rm -f "$mountpt/quota.user"
        fi
        if [ -f "$mountpt/quota.group" ]; then
            action $"Converting old group quota files: " \
            /sbin/convertquota -g "$mountpt" && \
            rm -f "$mountpt/quota.group"
        fi
        done
    fi
    action $"Checking local filesystem quotas: " /sbin/quotacheck -aRnug
fi

remount_needed() {
  local state oldifs
  [ "$READONLY" = "yes" ] && return 1
  state=`LC_ALL=C awk '/ \/ / && ($3 !~ /rootfs/) { print $4 }' /proc/mounts`
  oldifs=$IFS
  IFS=","
  for opt in $state ; do
      if [ "$opt" = "rw" ]; then
        IFS=$oldifs
        return 1
    fi
  done
  IFS=$oldifs
  return 0
}
 
# Remount the root filesystem read-write.
update_boot_stage RCmountfs
if remount_needed ; then
  action $"Remounting root filesystem in read-write mode: " mount -n -o remount,rw /
fi

# Clean up SELinux labels
if [ -n "$SELINUX_STATE" ]; then
   restorecon /etc/mtab /etc/ld.so.cache /etc/blkid/blkid.tab /etc/resolv.conf >/dev/null 2>&1
fi

if [ "$READONLY" != "yes" ] ; then
    # Clear mtab
    (> /etc/mtab) &> /dev/null

    # Remove stale backups
    rm -f /etc/mtab~ /etc/mtab~~

    # Enter mounted filesystems into /etc/mtab
    mount -f /
    mount -f /proc >/dev/null 2>&1
    mount -f /sys >/dev/null 2>&1
    mount -f /dev/pts >/dev/null 2>&1
    mount -f /proc/bus/usb >/dev/null 2>&1
fi

# Mount all other filesystems (except for NFS and /proc, which is already
# mounted). Contrary to standard usage,
# filesystems are NOT unmounted in single user mode.
if [ "$READONLY" != "yes" ] ; then
    action $"Mounting local filesystems: " mount -a -t nonfs,nfs4,smbfs,ncpfs,cifs,gfs,gfs2 -O no_netdev
else
    action $"Mounting local filesystems: " mount -a -n -t nfs4,smbfs,ncpfs,cifs,gfs,gfs2 -O no_netdev
fi

if [ -x /sbin/quotaon ]; then
    action $"Enabling local filesystem quotas: " /sbin/quotaon -aug
fi

# Check to see if a full relabel is needed
if [ -n "$SELINUX_STATE" -a "$READONLY" != "yes" ]; then 
    if [ -f /.autorelabel ] || strstr "$cmdline" autorelabel ; then
    relabel_selinux
    fi
else
    if [ -d /etc/selinux -a "$READONLY" != "yes" ]; then
        [ -f /.autorelabel ] || touch /.autorelabel
    fi
fi


# Start the graphical boot, if necessary and not done yet.
if strstr "$cmdline" rhgb && ! strstr "$cmdline" early-login && [ "$RHGB_STARTED" -eq 0 -a "$BOOTUP" = "color" -a "$GRAPHICAL" = "yes" -a -x /usr/bin/rhgb ]; then
   ( . /etc/sysconfig/i18n 2>/dev/null ; /usr/bin/rhgb )
   RHGB_STARTED=1
fi

# Initialize pseudo-random number generator
if [ -f "/var/lib/random-seed" ]; then
    cat /var/lib/random-seed > /dev/urandom
else
    [ "$READONLY" != "yes" ] && touch /var/lib/random-seed
fi
if [ "$READONLY" != "yes" ]; then
    chmod 600 /var/lib/random-seed
    dd if=/dev/urandom of=/var/lib/random-seed count=1 bs=512 2>/dev/null
fi

# Use the hardware RNG to seed the entropy pool, if available
#[ -x /sbin/rngd -a -c /dev/hw_random ] && rngd

if [ -f /etc/crypttab ]; then
    s=$"Starting disk encryption using the RNG:"
    echo "$s"
    init_crypto 1 && success "$s" || failure "$s"
    echo
fi

# Configure machine if necessary.
if [ -f /.unconfigured ]; then
    if [ -x /usr/bin/rhgb-client ] && /usr/bin/rhgb-client --ping ; then
    chvt 1
    fi

    if [ -x /usr/bin/system-config-keyboard ]; then
    /usr/bin/system-config-keyboard
    fi
    if [ -x /usr/bin/passwd ]; then 
        /usr/bin/passwd root
    fi
    if [ -x /usr/sbin/system-config-network-tui ]; then
    /usr/sbin/system-config-network-tui
    fi
    if [ -x /usr/sbin/timeconfig ]; then
    /usr/sbin/timeconfig
    fi
    if [ -x /usr/sbin/authconfig-tui ]; then
    /usr/sbin/authconfig-tui --nostart
    fi
    if [ -x /usr/sbin/ntsysv ]; then
    /usr/sbin/ntsysv --level 35
    fi

    # Reread in network configuration data.
    if [ -f /etc/sysconfig/network ]; then
    . /etc/sysconfig/network

    # Reset the hostname.
    action $"Resetting hostname ${HOSTNAME}: " hostname ${HOSTNAME}
    fi

    rm -f /.unconfigured

    if [ -x /usr/bin/rhgb-client ] && /usr/bin/rhgb-client --ping ; then
    chvt 8
    fi
fi

# Clean out /.
rm -f /fastboot /fsckoptions /forcefsck /.autofsck /forcequotacheck /halt \
    /poweroff /.suspended &> /dev/null

# Do we need (w|u)tmpx files? We don't set them up, but the sysadmin might...
_NEED_XFILES=
[ -f /var/run/utmpx -o -f /var/log/wtmpx ] && _NEED_XFILES=1

# Clean up /var.  I'd use find, but /usr may not be mounted.
for afile in /var/lock/* /var/run/* ; do
    if [ -d "$afile" ]; then
       case "$afile" in
        */news|*/mon)    ;;
        */sudo)        rm -f $afile/*/* ;;
        */vmware)    rm -rf $afile/*/* ;;
        */samba)    rm -rf $afile/*/* ;;
        */screen)    rm -rf $afile/* ;;
        */cvs)        rm -rf $afile/* ;;
        */dovecot)    rm -f $afile/*/* ;;
        */cups)        rm -f $afile/*/* ;;
        */libvirt)    rm -rf $afile/*/* ;;
        *)        rm -f $afile/* ;;
       esac
    else
       rm -f $afile
    fi
done
rm -f /var/lib/rpm/__db* &> /dev/null
rm -f /var/gdm/.gdmfifo &> /dev/null

# Reset pam_console permissions
[ -x /sbin/pam_console_apply ] && /sbin/pam_console_apply -r

{
# Clean up utmp/wtmp
> /var/run/utmp
touch /var/log/wtmp
chgrp utmp /var/run/utmp /var/log/wtmp
chmod 0664 /var/run/utmp /var/log/wtmp
if [ -n "$_NEED_XFILES" ]; then
  > /var/run/utmpx
  touch /var/log/wtmpx
  chgrp utmp /var/run/utmpx /var/log/wtmpx
  chmod 0664 /var/run/utmpx /var/log/wtmpx
fi

# Clean up various /tmp bits
[ -n "$SELINUX_STATE" ] && restorecon /tmp
rm -f /tmp/.X*-lock /tmp/.lock.* /tmp/.gdm_socket /tmp/.s.PGSQL.*
rm -rf /tmp/.X*-unix /tmp/.ICE-unix /tmp/.font-unix /tmp/hsperfdata_* \
       /tmp/kde-* /tmp/ksocket-* /tmp/mc-* /tmp/mcop-* /tmp/orbit-*  \
       /tmp/scrollkeeper-*  /tmp/ssh-* \
       /dev/.in_sysinit

# Make ICE directory
mkdir -m 1777 -p /tmp/.ICE-unix >/dev/null 2>&1
chown root:root /tmp/.ICE-unix
[ -n "$SELINUX_STATE" ] && restorecon /tmp/.ICE-unix >/dev/null 2>&1

#if [ -x /etc/init.d/diskdump ]; then
#    /etc/init.d/diskdump swapsavecore
#fi

# Start up swapping.
update_boot_stage RCswap
action $"Enabling /etc/fstab swaps: " swapon -a -e
if [ "$AUTOSWAP" = "yes" ]; then
    curswap=$(awk '/^\/dev/ { print $1 }' /proc/swaps | while read x; do get_numeric_dev dec $x ; echo -n " "; done)
    swappartitions=$(blkid -t TYPE=swap -o device)
    if [ x"$swappartitions" != x ]; then
        for partition in $swappartitions ; do
            [ ! -e $partition ] && continue
            majmin=$(get_numeric_dev dec $partition)
            echo $curswap | grep -qw "$majmin" || action $"Enabling local swap partitions: " swapon $partition
        done
    fi
fi

# Set up binfmt_misc
/bin/mount -t binfmt_misc none /proc/sys/fs/binfmt_misc > /dev/null 2>&1

# Initialize the serial ports.
if [ -f /etc/rc.serial ]; then
    . /etc/rc.serial
fi

# If they asked for ide-scsi, load it
if strstr "$cmdline" ide-scsi ; then
    modprobe ide-cd >/dev/null 2>&1
    modprobe ide-scsi >/dev/null 2>&1
fi

# Boot time profiles. Yes, this should be somewhere else.
if [ -x /usr/sbin/system-config-network-cmd ]; then
  if strstr "$cmdline" netprofile= ; then
    for arg in $cmdline ; do
        if [ "${arg##netprofile=}" != "${arg}" ]; then
        /usr/sbin/system-config-network-cmd --profile ${arg##netprofile=}
        fi
    done
  fi
fi

# Now that we have all of our basic modules loaded and the kernel going,
# let's dump the syslog ring somewhere so we can find it later
dmesg -s 131072 > /var/log/dmesg

# create the crash indicator flag to warn on crashes, offer fsck with timeout
touch /.autofsck &> /dev/null

if [ "$PROMPT" != no ]; then
    while :; do
    pid=$(/sbin/pidof getkey)
    [ -n "$pid" -o -e /var/run/getkey_done ] && break
    usleep 100000
    done
    [ -n "$pid" ] && kill -TERM "$pid" >/dev/null 2>&1
fi
} &
if strstr "$cmdline" confirm ; then
    touch /var/run/confirm
fi
if [ "$PROMPT" != "no" ]; then
    /sbin/getkey i && touch /var/run/confirm
    touch /var/run/getkey_done
fi
wait
[ "$PROMPT" != no ] && rm -f /var/run/getkey_done

# Let rhgb know that we're leaving rc.sysinit
if [ -x /usr/bin/rhgb-client ] && /usr/bin/rhgb-client --ping ; then
    /usr/bin/rhgb-client --sysinit
fi