#!/bin/bash
# Preinstall script

ZENTRAL_OSQUERY_ROOT="/usr/local/zentral/osquery"
OSQUERY_ROCKSDB_PATH="$ZENTRAL_OSQUERY_ROOT/db"
OSQUERY_ENROLL_SECRET_PATH="$ZENTRAL_OSQUERY_ROOT/enroll_secret.txt"
VENDOR_OSQUERY_PLIST="/Library/LaunchDaemons/com.facebook.osqueryd.plist"
LEGACY_WATCHDOG_PLIST="/Library/LaunchDaemons/io.zentral.osquery.watchdog.plist"
ZENTRAL_OSQUERY_PLIST="/Library/LaunchDaemons/pro.zentral.osqueryd.plist"

# unload and disable the standard Osquery launch daemon
if [[ -e "$VENDOR_OSQUERY_PLIST" ]]; then
    /bin/launchctl unload -w "$VENDOR_OSQUERY_PLIST"
    rm "$VENDOR_OSQUERY_PLIST"
fi

# unload and disable the legacy watchdog if necessary
if [[ -e "$LEGACY_WATCHDOG_PLIST" ]]; then
    /bin/launchctl unload -w "$LEGACY_WATCHDOG_PLIST"
    rm "$LEGACY_WATCHDOG_PLIST"
fi

# unload the Zentral Osquery launch daemon if it already exists
if [[ -e "$ZENTRAL_OSQUERY_PLIST" ]]; then
    /bin/launchctl unload "$ZENTRAL_OSQUERY_PLIST"
fi

# delete existing osquery DB to force enrollment
if [[ -d "$OSQUERY_ROCKSDB_PATH" ]]; then
  /bin/rm -rf "$OSQUERY_ROCKSDB_PATH"
fi

# create directory for osquery and rocksDB
/bin/mkdir -p "$OSQUERY_ROCKSDB_PATH"
/usr/sbin/chown -R root:admin "$ZENTRAL_OSQUERY_ROOT"

# create enrollment file from a secret
echo "%ENROLL_SECRET_SECRET%" > "$OSQUERY_ENROLL_SECRET_PATH"

# lock down enrollment secret file
/bin/chmod 400 "$OSQUERY_ENROLL_SECRET_PATH"
/usr/sbin/chown root:admin "$OSQUERY_ENROLL_SECRET_PATH"

exit 0
