#!/bin/sh
### BEGIN INIT INFO
# Provides:          eudev-finish
# Required-Start:    eudev $local_fs
# Required-Stop:
# Default-Start:     S
# Default-Stop:
# Short-Description: Save the udev rules generated during early boot
# Description:       Append the rules that write_net_rules saved in /run/udev
#                    while the root file system was read-only to their files
#                    in /etc/udev/rules.d.
### END INIT INFO

PATH="/sbin:/bin:/usr/sbin:/usr/bin"

. /lib/lsb/init-functions

case "$1" in
    start)
    for file in /run/udev/tmp-rules--*; do
      [ -e "$file" ] || continue
      name="${file##*/tmp-rules--}"
      dest="/etc/udev/rules.d/$name"
      # take the lock of write_net_rules (lock_rules_file of
      # rule_generator.functions), so that no rule that it writes at the
      # same time gets lost
      lock="/run/udev/.lock-$name"
      retry=30
      while ! mkdir "$lock" 2>/dev/null; do
        if [ $retry -eq 0 ]; then
          log_warning_msg "Could not lock $dest, $file not saved"
          continue 2
        fi
        sleep 1
        retry=$((retry - 1))
      done
      if cat "$file" >> "$dest"; then
        rm -f "$file"
      else
        log_warning_msg "Could not save $file to $dest"
      fi
      rmdir "$lock"
    done
    ;;

    stop|restart|force-reload)
    ;;

    status)
    # a task that runs once at boot has no status
    exit 4
    ;;

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

exit 0
