#!/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_flag() {
	local file="$1"
	local flag="$2" # actually flag pattern
	local value="$3"
	local position="${4:-1}" # after which flag insert new flag
	
	if grep -qEe "--${flag}[\=\s].*?" "${file}";
	then
		sed -i -Ee "s/--${flag}([\s\=]+).*/--${flag}\1${value}/g" "${file}"
	else
	    sed -i -e "/--${position}/a\--${flag}=${value}" "${file}"
	fi
}

set_flag() {
   	local file="${flags_file}"
	local flag="$1" # actually flag pattern
	local value="$2"
	local position="${3:-disable_extensions}" # after which flag insert new flag

    __set_flag "${file}" "${flag}" "${value}" "${position}"
}

false_flag () {
    set_flag "$1" "false"
}

set_tls_hostname 'cos.sec.yandex.net'
false_flag 'audit_allow_process_events' || true

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
