# arg 1:  the new package version
# arg 2:  the old package version

KERNEL_NAME=-grsec
KERNEL_VERSION=3.15.6.201407232200-1-grsec

_add_groups() {
  if getent group tpe-trusted >/dev/null; then
    groupmod -g 200 -n tpe tpe-trusted
  fi

  if ! getent group tpe >/dev/null; then
    groupadd -g 200 -r tpe
  fi

  if ! getent group audit >/dev/null; then
    groupadd -g 201 -r audit
  fi

  if getent group socket-deny-all >/dev/null; then
    groupmod -g 202 socket-deny-all
  else
    groupadd -g 202 -r socket-deny-all
  fi

  if getent group socket-deny-client >/dev/null; then
    groupmod -g 203 socket-deny-client
  else
    groupadd -g 203 -r socket-deny-client
  fi

  if getent group socket-deny-server >/dev/null; then
    groupmod -g 204 socket-deny-server
  else
    groupadd -g 204 -r socket-deny-server
  fi
}

_remove_groups() {
  for group in tpe socket-deny-server socket-deny-client socket-deny-all; do
    if getent group $group >/dev/null; then
      groupdel $group
    fi
  done
}

post_install() {
  # updating module dependencies
  echo ">>> Updating module dependencies. Please wait ..."
  depmod ${KERNEL_VERSION}
  echo ">>> Generating initial ramdisk, using mkinitcpio.  Please wait..."
  mkinitcpio -p linux${KERNEL_NAME}

  _add_groups
}

post_upgrade() {
  if findmnt --fstab -uno SOURCE /boot &>/dev/null && ! mountpoint -q /boot; then
    echo "WARNING: /boot appears to be a separate partition but is not mounted."
  fi

  if getent group proc-trusted >/dev/null; then
    groupdel proc-trusted
  fi

  # updating module dependencies
  echo ">>> Updating module dependencies. Please wait ..."
  depmod ${KERNEL_VERSION}
  echo ">>> Generating initial ramdisk, using mkinitcpio.  Please wait..."
  mkinitcpio -p linux${KERNEL_NAME}

  if [ $(vercmp $2 3.13) -lt 0 ]; then
    echo ">>> WARNING: AT keyboard support is no longer built into the kernel."
    echo ">>>          In order to use your keyboard during early init, you MUST"
    echo ">>>          include the 'keyboard' hook in your mkinitcpio.conf."
  fi

  _add_groups
}

post_remove() {
  # also remove the compat symlinks
  rm -f boot/initramfs-linux${KERNEL_NAME}.img
  rm -f boot/initramfs-linux${KERNEL_NAME}-fallback.img

  _remove_groups
}
