#!/bin/sh

cleanup() {
    test -d '/tmp' && \
        /usr/bin/find '/tmp' -type f -name "osqueryd*" -delete >/dev/null 2>&1 || \
        /bin/true
    test -d '/var/osquery/osquery.db' && \
        /usr/bin/find '/var/osquery/osquery.db/' -type f -delete >/dev/null 2>&1 || \
        /bin/true
    test -d '/usr/share/osquery/osquery.dbq' && \
        /usr/bin/find '/var/osquery/osquery.dbq/' -type f -delete >/dev/null 2>&1 || \
        /bin/true
}

set_tls_hostname() {
    sed -i "s/--tls_hostname=.*/--tls_hostname=$1/g" "/etc/osquery/osquery.flags"
}

set_tls_hostname 'cos.sec.yandex.net'

case "$1" in
  configure|2)
    if which /bin/systemctl >/dev/null && pidof systemd-journald >/dev/null 2>&1 ; then
    	/bin/systemctl daemon-reload >/dev/null 2>&1
    	/bin/systemctl enable osqueryd >/dev/null 2>&1
    	/bin/systemctl stop osqueryd >/dev/null 2>&1
        cleanup
        /bin/systemctl restart osqueryd || exit $?
    elif which invoke-rc.d >/dev/null && which update-rc.d >/dev/null 2>&1 ; then
    	update-rc.d osqueryd defaults >/dev/null 2>&1
        invoke-rc.d osqueryd stop >/dev/null 2>&1
        cleanup
    	invoke-rc.d osqueryd restart || exit $?
    elif which initctl >/dev/null 2>&1 ; then
    	initctl reload-configuration >/dev/null 2>&1
        initctl stop osqueryd >/dev/null 2>&1
        cleanup
    	initctl restart osqueryd || exit $?
    else
        service osqueryd stop >/dev/null 2>&1
        cleanup
        service osqueryd restart || exit $?
    fi
    ;;
  *)
    exit 0
    ;;
esac

exit 0
