#!/bin/sh

set -e

case "$1" in
    configure)

        # Create user
        if ! getent passwd xmr-stak-cpu >/dev/null; then
          adduser --disabled-password --quiet --system \
            --home /var/lib/xmr-stak-cpu --no-create-home \
            xmr-stak-cpu
        fi

        # Enable huge memory page
        sysctl_conf=/etc/sysctl.d/50-xmr-stak-cpu.conf
	current_hugepages_count=`sysctl vm.nr_hugepages -n`
        if [ ${current_hugepages_count} -lt 128 ]; then
            echo "Current hugepages count is ${current_hugepages_count} while xmr-stak-cpu recommends 128"
            if [ -f "${sysctl_conf}" ]; then
                echo "However ${sysctl_conf} already exists so I will not try to fix this issue"
                echo "Edit the file yourself and set value to at least 128"
            else
                echo "I will now create ${sysctl_conf} to raise vm.nr_hugepages to 128"
                echo "Edit the file yourself if you do not want this on increase value for other apps"
                echo "# https://wiki.debian.org/Hugepages" > "${sysctl_conf}"
                echo "# https://github.com/fireice-uk/xmr-stak-cpu/blob/master/README.md#common-issues" >> "${sysctl_conf}"
                echo "vm.nr_hugepages=128" >> "${sysctl_conf}"
                sysctl -q -p "${sysctl_conf}"
                echo 
            fi
        else
            echo "Current hugepages count is ${current_hugepages_count} which is sufficient"
            if [ -f "${sysctl_conf}" ]; then
                echo "File ${sysctl_conf} already exists, edit it if you need to change this value"
            else
                echo "I will now create ${sysctl_conf} but with commented settings as your system"
                echo "seems to be already overriding this value"
                echo "# https://wiki.debian.org/Hugepages" > "${sysctl_conf}"
                echo "# https://github.com/fireice-uk/xmr-stak-cpu/blob/master/README.md#common-issues" >> "${sysctl_conf}"
                echo "# Line below is commented because your system was already having" >> "${sysctl_conf}"
                echo "# hugepage enabled when installing this package" >> "${sysctl_conf}"
                echo "#vm.nr_hugepages=128" >> "${sysctl_conf}"
            fi
        fi

        # Display doc
        echo
        cat /usr/share/doc/xmr-stak-cpu/README.Debian
        sleep 15
        echo

    ;;

    abort-upgrade|abort-remove|abort-deconfigure)
    ;;

    *)
        echo "postinst called with unknown argument \`$1'" >&2
        exit 1
    ;;
esac

#DEBHELPER#

exit 0
