#!/usr/bin/env /lib/runit/invoke-run
#Copyright: 2026 Aitor <aitor@genuen.org>
#License: CC0-1.0
#Comment: ported for runit-services testing (eudev)

# Conflicts with vdev: enable only one device manager in testing.
exec 2>&1
command=/sbin/udevd
[ -x "$command" ] || exit 162

tmpfs_size="10M"
[ -e /etc/udev/udev.conf ] && . /etc/udev/udev.conf

if [ ! -e /proc/filesystems ]; then
  echo "eudev requires a mounted procfs"
  exit 162
fi
if ! grep -q '[[:space:]]devtmpfs$' /proc/filesystems; then
  echo "eudev requires devtmpfs support"
  exit 162
fi
if [ ! -d /sys/class/ ]; then
  echo "eudev requires a mounted sysfs"
  exit 162
fi

unmount_devpts() {
  mountpoint -q /dev/pts/ && umount -n -l /dev/pts/ || true
  mountpoint -q /dev/shm/ && umount -n -l /dev/shm/ || true
}
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 0
  fi
  mount -n -o nosuid,size=$tmpfs_size,mode=0755 -t devtmpfs devtmpfs /dev
}

if [ -w /sys/kernel/uevent_helper ]; then
  echo > /sys/kernel/uevent_helper
fi
if ! mountpoint -q /dev/; then
  unmount_devpts
  mount_devtmpfs || exit 162
  [ -d /proc/1 ] || mount -n /proc
fi

if [ -e /lib/modules/$(uname -r)/modules.devname ] && [ -x /bin/kmod ]; then
  /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 -p $name ;;
    esac
    [ -x /sbin/restorecon ] && /sbin/restorecon $name
  done
fi

udevadm info --cleanup-db 2>/dev/null || true
[ -x /sbin/restorecon ] && /sbin/restorecon -R /dev || true

(
  # Coldplug after udevd is listening
  for i in 1 2 3 4 5 6 7 8 9 10; do
    udevadm control --ping >/dev/null 2>&1 && break
    sleep 0.2
  done
  udevadm trigger --type=subsystems --action=add || true
  udevadm trigger --type=devices --action=add || true
  udevadm settle || true
  if [ -e /sbin/MAKEDEV ]; then
    ln -sf /sbin/MAKEDEV /dev/MAKEDEV
  else
    ln -sf /bin/true /dev/MAKEDEV
  fi
) &

# Foreground: no --daemon
exec $command
