#!/bin/sh -e
### BEGIN INIT INFO
# Provides:          eudev udev
# Required-Start:    mountkernfs
# Required-Stop:     umountroot
# Default-Start:     S
# Default-Stop:      0 6
# Short-Description: Start udevd, populate /dev and load drivers.
### END INIT INFO

PATH="/lib/udev:/sbin:/bin:/usr/bin"
NAME="udevd"
DAEMON="/sbin/udevd"
DAEMON_ARGS="--daemon"
DESC="hot-plug events dispatcher"

# we need to unmount /dev/pts/ and remount it later over the devtmpfs
unmount_devpts() {
  if mountpoint -q /dev/pts/; then
    umount -n -l /dev/pts/
  fi

  if mountpoint -q /dev/shm/; then
    umount -n -l /dev/shm/
  fi
}

# mount a devtmpfs over /dev, if somebody did not already do it
mount_devtmpfs() {
  if grep -E -q "^[^[:space:]]+ /dev devtmpfs" /proc/mounts; then
    mount -n -o remount,nosuid,size=$tmpfs_size,mode=0755 -t devtmpfs devtmpfs /dev
    return
  fi

  if ! mount -n -o nosuid,size=$tmpfs_size,mode=0755 -t devtmpfs devtmpfs /dev; then
    log_failure_msg "eudev requires devtmpfs support, $NAME not started"
    log_end_msg 1
  fi

  return 0
}

create_dev_makedev() {
  if [ -e /sbin/MAKEDEV ]; then
    ln -sf /sbin/MAKEDEV /dev/MAKEDEV
  else
    ln -sf /bin/true /dev/MAKEDEV
  fi
}

# shell version of /usr/bin/tty
my_tty() {
  [ -x /bin/readlink ] || return 0
  [ -e /proc/self/fd/0 ] || return 0
  readlink --silent /proc/self/fd/0 || true
}

warn_if_interactive() {
  if [ "$RUNLEVEL" = "S" -a "$PREVLEVEL" = "N" ]; then
    return
  fi

  TTY=$(my_tty)
  if [ -z "$TTY" -o "$TTY" = "/dev/console" -o "$TTY" = "/dev/null" ]; then
    return
  fi

  printf "\n\n\nIt has been detected that the command\n\n\t$0 $*\n\n"
  printf "has been run from an interactive shell.\n"
  printf "It will probably not do what you expect, so this script will wait\n"
  printf "60 seconds before continuing. Press ^C to stop it.\n"
  printf "RUNNING THIS COMMAND IS HIGHLY DISCOURAGED!\n\n\n\n"
  sleep 60
}

make_static_nodes() {
  [ -e /lib/modules/$(uname -r)/modules.devname ] || return 0
  [ -x /bin/kmod ] || return 0

  /bin/kmod static-nodes --format=tmpfiles --output=/proc/self/fd/1 | \
  while read type name mode uid gid age arg; do
    [ -e $name ] && continue
    case "$type" in
      c|b|c!|b!) mknod -m $mode $name $type $(echo $arg | sed 's/:/ /') ;;
      d|d!) mkdir $name ;;
      *) echo "unparseable line ($type $name $mode $uid $gid $age $arg)" >&2 ;;
    esac

    if [ -x /sbin/restorecon ]; then
      /sbin/restorecon $name
    fi
  done
}


# udev.conf and its drop-ins, read the way udevd reads them (see udev.conf(5)):
# the first udev.conf of these directories, unless an empty file or a symlink
# to /dev/null masks it and the later ones, then the *.conf files in their
# udev.conf.d subdirectories, sorted by their names, where a file overrides
# or masks the files with the same name in the later directories
UDEV_CONF_DIRS="/etc/udev /run/udev /usr/local/lib/udev /usr/lib/udev"

udev_conf_is_mask() {
  [ "$(readlink -f "$1")" = /dev/null ] || { [ -f "$1" ] && [ ! -s "$1" ]; }
}

# the KEY=VALUE lines of a file, parsed like udevd does: whitespace around the
# key and the value is ignored, a value may be quoted with " or ', and
# comments, lines without "=", empty values and values with unbalanced quotes
# are skipped; each key sets the shell variable of the same name, which must
# be lowercase, like the keys of udev.conf, so that nothing else changes
udev_conf_read_file() {
  local line key val quote
  while IFS= read -r line || [ -n "$line" ]; do
    line=${line#"${line%%[![:space:]]*}"}
    case "$line" in
      ''|'#'*) continue ;;
      *=*) ;;
      *) continue ;;
    esac
    key=${line%%=*}
    key=${key%"${key##*[![:space:]]}"}
    val=${line#*=}
    val=${val#"${val%%[![:space:]]*}"}
    val=${val%"${val##*[![:space:]]}"}
    [ -n "$key" ] && [ -n "$val" ] || continue
    case "$val" in
      \"*|\'*)
        quote=${val%"${val#?}"}
        [ "${#val}" -gt 1 ] && [ "${val#"${val%?}"}" = "$quote" ] || continue
        val=${val#?}
        val=${val%?}
        ;;
    esac
    case "$key" in
      [!a-z]*|*[!a-z0-9_]*) continue ;;
    esac
    eval "$key=\$val"
  done < "$1"
}

read_udev_conf() {
  local dir file main name seen tab list dropins
  main=
  for dir in $UDEV_CONF_DIRS; do
    file=$dir/udev.conf
    [ -e "$file" ] || [ -L "$file" ] || continue
    udev_conf_is_mask "$file" && break
    [ -f "$file" ] || continue
    main=$file
    break
  done
  tab=$(printf '\t')
  list=$(for dir in $UDEV_CONF_DIRS; do
      for file in "$dir"/udev.conf.d/*.conf; do
        [ -e "$file" ] || [ -L "$file" ] || continue
        printf '%s\t%s\n' "${file##*/}" "$file"
      done
    done | LC_ALL=C sort -s -t "$tab" -k1,1)
  seen=/
  dropins=
  while IFS="$tab" read -r name file; do
    [ -n "$name" ] || continue
    case "$seen" in
      */"$name"/*) continue ;;
    esac
    if udev_conf_is_mask "$file"; then
      seen="$seen$name/"
      continue
    fi
    [ -f "$file" ] || continue
    seen="$seen$name/"
    # a udev.conf that is also a drop-in is read only as the drop-in
    [ -z "$main" ] || [ ! "$main" -ef "$file" ] || main=
    dropins="$dropins$file
"
  done <<EOF
$list
EOF
  [ -z "$main" ] || udev_conf_read_file "$main"
  while IFS= read -r file; do
    [ -z "$file" ] || udev_conf_read_file "$file"
  done <<EOF
$dropins
EOF
}

##############################################################################

[ -x $DAEMON ] || exit 0


# defaults
tmpfs_size="10M"

read_udev_conf

. /lib/lsb/init-functions

if [ ! -e /proc/filesystems ]; then
  log_failure_msg "eudev requires a mounted procfs, $NAME not started"
  log_end_msg 1
fi

if ! grep -q '[[:space:]]devtmpfs$' /proc/filesystems; then
  log_failure_msg "eudev requires devtmpfs support, $NAME not started"
  log_end_msg 1
fi

if [ ! -d /sys/class/ ]; then
  log_failure_msg "eudev requires a mounted sysfs, $NAME not started"
  log_end_msg 1
fi

# System processes and/or kernel threads are surrounded by brackets: [...]
if ! ps --no-headers --format args ax | grep -E -q '^\['; then
  log_warning_msg "eudev does not support containers, $NAME not started"
  exit 0
fi

if [ -d /sys/class/mem/null -a ! -L /sys/class/mem/null ] || \
   [ -e /sys/block -a ! -e /sys/class/block ]; then
  log_warning_msg "CONFIG_SYSFS_DEPRECATED must not be selected"
  log_warning_msg "Booting will continue in 30 seconds but many things will be broken"
  sleep 30
fi

# When modifying this script, do not forget that between the time that the
# new /dev has been mounted and udevadm trigger has been run there will be
# no /dev/null. This also means that you cannot use the "&" shell command.

case "$1" in
    start)
    if [ ! -e "/run/udev/" ]; then
	warn_if_interactive
    fi

    if [ -w /sys/kernel/uevent_helper ]; then
	echo > /sys/kernel/uevent_helper
    fi

    if ! mountpoint -q /dev/; then
	unmount_devpts
	mount_devtmpfs
	[ -d /proc/1 ] || mount -n /proc
    fi

    make_static_nodes

    # clean up parts of the database created by the initramfs udev
    udevadm info --cleanup-db

    # set the SELinux context for devices created in the initramfs
    [ -x /sbin/restorecon ] && /sbin/restorecon -R /dev

    log_daemon_msg "Starting $DESC" "$NAME"
    if start-stop-daemon --start --name $NAME --exec $DAEMON --quiet \
	-- $DAEMON_ARGS; then
      log_end_msg $?
    else
	log_warning_msg $?
	log_warning_msg "Waiting 15 seconds and trying to continue anyway"
	sleep 15
    fi

    log_action_begin_msg "Synthesizing the initial hotplug events (subsystems)"
    if udevadm trigger --type=subsystems --action=add; then
	log_action_end_msg $?
    else
	log_action_end_msg $?
    fi

    log_action_begin_msg "Synthesizing the initial hotplug events (devices)"
    if udevadm trigger --type=devices --action=add; then
	log_action_end_msg $?
     else
	log_action_end_msg $?
    fi

    create_dev_makedev

    # wait for the udevd childs to finish
    log_action_begin_msg "Waiting for /dev to be fully populated"
    if udevadm settle; then
	log_action_end_msg 0
    else
	log_action_end_msg 0 'timeout'
    fi
    ;;

    stop)
    log_daemon_msg "Stopping $DESC" "$NAME"
    if start-stop-daemon --stop --name $NAME --quiet --oknodo --retry 5; then
      log_end_msg $?
    else
      log_end_msg $?
    fi
    ;;

    restart)
    log_daemon_msg "Stopping $DESC" "$NAME"
    if start-stop-daemon --stop --name $NAME --quiet --oknodo --retry 5; then
      log_end_msg $?
    else
      log_end_msg $? || true
    fi

    log_daemon_msg "Starting $DESC" "$NAME"
    if start-stop-daemon --start --name $NAME --exec $DAEMON --quiet \
      -- $DAEMON_ARGS; then
      log_end_msg $?
    else
      log_end_msg $?
    fi
    ;;

    reload|force-reload)
    udevadm control --reload-rules
    ;;

    status)
    status_of_proc $DAEMON $NAME && exit 0 || exit $?
    ;;

    *)
    echo "Usage: /etc/init.d/eudev {start|stop|restart|reload|force-reload|status}" >&2
    exit 1
    ;;
esac

exit 0

