#!/bin/sh

set -eu

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

random_seed=/var/lib/tuxenix/random-seed

ensure_machine_id() {
  if [ ! -s /etc/machine-id ]; then
    if command -v dbus-uuidgen >/dev/null 2>&1; then
      dbus-uuidgen --ensure=/etc/machine-id
    elif [ -r /proc/sys/kernel/random/uuid ]; then
      tr -d - < /proc/sys/kernel/random/uuid > /etc/machine-id
    fi
  fi

  mkdir -p /var/lib/dbus
  ln -snf /etc/machine-id /var/lib/dbus/machine-id
}

restore_random_seed() {
  if [ -r "${random_seed}" ]; then
    cat "${random_seed}" > /dev/urandom
  fi
}

save_random_seed() {
  mkdir -p /var/lib/tuxenix
  umask 0077
  dd if=/dev/urandom of="${random_seed}" bs=512 count=1 2>/dev/null
}

configure_hostname() {
    if [ -s /etc/hostname ]; then
        sed -n '1p' /etc/hostname > /proc/sys/kernel/hostname
    fi
}

case "${1:-}" in
  start)
    mkdir -p /tmp /var/log /var/lib/tuxenix
    chmod 1777 /tmp
    ensure_machine_id
    restore_random_seed
    configure_hostname
    if command -v ip >/dev/null 2>&1; then
      ip link set lo up
    elif command -v ifconfig >/dev/null 2>&1; then
      ifconfig lo up
    fi

    if command -v systemd-tmpfiles >/dev/null 2>&1; then
      systemd-tmpfiles --remove --create --boot
    fi

    if command -v sysctl >/dev/null 2>&1; then
      sysctl --system
    fi
    ;;
  stop)
    save_random_seed
    ;;
  *)
    echo "usage: $0 {start|stop}" >&2
    exit 2
    ;;
esac
