#!/bin/bash

sd_booted() {
  [[ -d run/systemd/system && ! -L run/systemd/system ]]
}

services_needing_restart() {
  systemctl list-units --state=running --plain --quiet 'systemd-*.service' \
    | cut -d' ' -f1 \
    | grep -Ev '^systemd-(logind|networkd)\.service$' \
    | grep -Ev '^systemd-.*@.*\.service$'
}

post_common() {
  systemd-sysusers
  journalctl --update-catalog

  if ! grep -qe '^/usr/bin/systemd-home-fallback-shell$' etc/shells; then
    echo '/usr/bin/systemd-home-fallback-shell' >> etc/shells
  fi
}

post_install() {
  systemd-machine-id-setup

  post_common "$@"

  # enable some services by default, but don't track them
  systemctl enable \
    getty@.service \
    remote-fs.target \
    systemd-userdbd.socket

  # group 'systemd-journal-remote' is created by systemd-sysusers
  mkdir -m2755 var/log/journal/remote
  chgrp systemd-journal-remote var/log/journal/remote
}

_260_1_changes() {
  systemctl enable getty@.service
}

post_upgrade() {
  post_common "$@"

  if sd_booted; then
    # reexec systemd system instance
    systemctl --system daemon-reexec

    # reexec systemd user instances
    systemctl reload 'user@*.service'

    # mark systemd services for later restart
    for UNIT in $(services_needing_restart); do
      systemctl set-property --runtime "${UNIT}" Markers=needs-restart
    done
  fi

  # show for feature release: 255 -> 256 -> 257 -> ...
  if [ $(vercmp "${1%%[!0-9]*}" "${2%%[!0-9]*}") -ne 0 ]; then
    cat <<-EOM
	:: This is a systemd feature update. You may want to have a look at
	   NEWS for what changed, or if you observe unexpected behavior:
	     /usr/share/doc/systemd/NEWS
	EOM
  fi

  # This matches if old package full version string is older the given string,
  # so give the first version including the fix!
  # Create a matching function: '259.1-2' -> _259_1_2_changes()
  local ver upgrades=(
    '260-1'
  )

  for ver in "${upgrades[@]}"; do
    if [[ $(vercmp "$ver" "$2") -eq 1 ]]; then
      "_${ver//[.-]/_}_changes"
    fi
  done
}

post_remove() {
  sed -i -r '/^\/usr\/bin\/systemd-home-fallback-shell$/d' etc/shells
}

# vim:set ts=2 sw=2 et:
