# Change these to modify the ownership of sabnzbd
# If you change this here, you also have to change
# the user and group in the systemd service file.
SABNZBD_USER="sabnzbd"
SABNZBD_GROUP="sabnzbd"

SABNZBD_DIR="/opt/sabnzbd"  # should not be changed

## arg 1:  the new package version
post_install() {
  # add x-nzb mimetype
  if [[ -f /usr/bin/xdg-mime ]]; then
    xdg-mime install --mode system "${SABNZBD_DIR}/x-nzb.xml"
    xdg-icon-resource install --context mimetypes --size 64 "${SABNZBD_DIR}/nzb-2.png" application-x-nzb
  fi

  post_upgrade

  cat << "EOM"
==> If you want to associate .nzb-files with SABnzbd, run 'xdg-mime default sabnzbd.desktop applications/x-nzb'
EOM
}

## arg 1:  the new package version
## arg 2:  the old package version
pre_upgrade() {
  PID="$(pgrep -f SABnzbd.py)"

  if [ -n "${PID}" ];then
    systemctl stop sabnzbd.service
  fi
}

## arg 1:  the new package version
## arg 2:  the old package version
post_upgrade() {
  # if the group or user already exists, the request will be denied 
  # and all original settings will be retained
  if [ "$SABNZBD_GROUP" == "sabnzbd" ]; then
    groupadd -r sabnzbd &> /dev/null
  fi

  if [ "$SABNZBD_USER" == "sabnzbd" ]; then
  useradd -s /sbin/nologin -c "SABnzbd user" -d "${SABNZBD_DIR}" \
          -g sabnzbd -r sabnzbd &> /dev/null
  fi

  chown -R "${SABNZBD_USER}:${SABNZBD_GROUP}" "${SABNZBD_DIR}"
}

## arg 1:  the old package version
pre_remove() {
  pre_upgrade

  if [[ -f /usr/bin/xdg-mime ]]; then
    xdg-mime uninstall --mode system "${SABNZBD_DIR}/x-nzb.xml"
    xdg-icon-resource uninstall --context mimetypes --size 64 application-x-nzb
  fi
}

## arg 1:  the old package version
post_remove() {
  # only delete if user is sabnzbd
  userdel sabnzbd &> /dev/null 
  groupdel sabnzbd &> /dev/null || /bin/true
  echo "==> There may be some files left in ${SABNZBD_DIR}."
}

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