#!/bin/sh
#
# Manticore Search SysD Unit-generator with libjmalloc.so script
#

is_jemalloc() {
        STATUS_THP_SYSTEM=0
        STATUS_THPD_SYSTEM=0
        jemalloc_disabled=0
        jemalloc_preload=true

        if [ -f /etc/default/manticore ]; then
                jemalloc_disabled=$(awk '/^jemalloc_disabled$/ {print $1;}' /etc/default/manticore | wc -l)
        fi

        if [ -f /sys/kernel/mm/transparent_hugepage/enabled ]; then
                CONTENT_TRANSHP=$(</sys/kernel/mm/transparent_hugepage/enabled)
                STATUS_THP_SYSTEM=$(echo $CONTENT_TRANSHP | grep -cv '\[never\]')
                if [ -f /sys/kernel/mm/transparent_hugepage/defrag ]; then
                        CONTENT_TRANSHP_DEFRAG=$(</sys/kernel/mm/transparent_hugepage/defrag)
                        STATUS_THPD_SYSTEM=$(echo $CONTENT_TRANSHP_DEFRAG | grep -cv '\[never\]')
                fi
        fi

        if [ $jemalloc_disabled == 0 ] && [ $STATUS_THP_SYSTEM -eq 0 ] && [ $STATUS_THPD_SYSTEM -eq 0 ]; then
                for libjemall in "/usr/lib64" "/usr/lib/x86_64-linux-gnu" "/usr/lib" "/usr/lib/i386-linux-gnu"; do
                        if [ -r "$libjemall/libjemalloc.so.1" ]; then
                                JEMALLOC_LOCATION="$libjemall/libjemalloc.so.1"
                                break
                        fi
                done
        fi
        if [ -z $JEMALLOC_LOCATION ]; then
        	jemalloc_preload=false
        else
		jemalloc_preload=true
        fi
}

is_jemalloc

if [ ! -e /usr/lib/systemd/system/manticore.service ]; then
	M_UNIT_FILE="/usr/lib/systemd/system/manticore.service"
else
	M_UNIT_FILE="$2/manticore.service"
fi

if [ $jemalloc_preload ]; then 
cat << EOF > $M_UNIT_FILE
[Unit]
Description=Manticore Search Engine
After=network.target remote-fs.target nss-lookup.target
After=syslog.target

[Service]
Type=forking
User=manticore
Group=manticore
# Run ExecStartPre with root-permissions
PermissionsStartOnly=true
ExecStartPre=/usr/bin/install -omanticore -gmanticore -m755 -d /var/run/manticore
# Run ExecStart with User=manticore / Group=manticore
Environment=LD_PRELOAD=$JEMALLOC_LOCATION
ExecStart=/usr/bin/searchd --config /etc/manticoresearch/manticore.conf \$_ADDITIONAL_SEARCHD_PARAMS
ExecStop=/usr/bin/searchd --config /etc/manticoresearch/manticore.conf --stopwait
KillMode=process
KillSignal=SIGTERM
SendSIGKILL=no
LimitNOFILE=infinity
LimitCORE=infinity
LimitMEMLOCK=infinity
Restart=on-failure
TimeoutStartSec=infinity
PIDFile=/var/run/manticore/searchd.pid

[Install]
WantedBy=multi-user.target
Alias=manticore.service
Alias=searchd.service
EOF
fi
