#!/bin/sh -e

NAME=fah-client
CLIENT_HOME=/var/lib/$NAME

case "$1" in
  install)
    # Old v7 init script is broken and does not stop when told so
    if [ -e /etc/init.d/FAHClient ]; then
      systemctl kill FAHClient 2>/dev/null || true

      # Missing PID file in init scripts cripples systemd monitoring,
      # requiring manual waiting for process exit
      TRY=0
      while pgrep -x FAHClient >/dev/null && [ $TRY -lt 120 ]; do
        sleep 1
        TRY=$((TRY+1))
      done
    fi

    # Create group if it does not exist
    if ! getent group $NAME >/dev/null; then
      groupadd --system $NAME || true
    fi

    # Create user if it does not exist
    if ! getent passwd $NAME >/dev/null; then
      useradd --system --gid $NAME --shell /usr/sbin/nologin \
        --home-dir $CLIENT_HOME --no-create-home \
        --groups video,render $NAME || true
    fi
    ;;

  upgrade)
    # Remove broken symlink installed by previous v8 packages
    if dpkg --compare-versions "$2" lt 8.2.1; then
      systemctl -q disable $NAME || true
    fi
    ;;
esac
