# Most (except tmpfile, ldconfig, and try-restart) of this is boring
# (and perhaps fragile...) logic to migrate from the old (and possibly
# broken) smbd systemd units.

to_enable=""
to_start=""

for i in {smbd,nmbd,winbindd}.service smbd.socket 'smbd@*.service'; do
  if [ -d /run/systemd/system ] && systemctl is-active --quiet "${i}"; then
    echo "Stopping ${i} from old samba installation ..."
    systemctl stop "${i}"

    case "${i}" in
      *@* ) ;;
      * ) to_start="${to_start} ${i%d.*}.service"
    esac
  fi

  # systemctl is-enabled doesn't work on such a dangling symlink.
  if [ -L /etc/systemd/system/*.wants/"${i}" ]; then
    echo "Disabling ${i} from old samba installation ..."
    systemctl disable "${i}"

    case "${i}" in
      *@* ) ;;
      * ) to_enable="${to_enable} ${i%d.*}.service"
    esac
  fi
done

systemd-tmpfiles --create samba.conf
ldconfig

if [ -d /run/systemd/system ]; then
  echo "Restarting the running Samba service units (if any) ..."
  systemctl daemon-reload
  systemctl try-restart {smb,nmb,winbind,ctdb,samba,samba-bgqd}.service
fi

if [ -n "${to_enable}" ]; then
  echo "Migrating from old Samba build: enabling ${to_enable} ..."
  systemctl enable ${to_enable}
fi

if [ -n "${to_start}" ]; then
  echo "Migrating from old Samba build: starting ${to_start} ..."
  systemctl start ${to_start}
fi
