#!/usr/bin/env bash

# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

set -eu

LOG_DIR=/var/log/mozillavpn

mkdir -p $LOG_DIR
exec 2>&1 > $LOG_DIR/postinstall.log

echo "Running postinstall at $(date)"

DAEMON_PLIST_PATH="/Library/LaunchDaemons/org.mozilla.macos.FirefoxVPN.daemon.plist"

DAEMON_PLIST=$(cat <<-EOM
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
        <dict>
                <key>Label</key>
                <string>org.mozilla.macos.FirefoxVPN.daemon</string>
                <key>ProgramArguments</key>
                <array>
                        <string>/Applications/Mozilla VPN.app/Contents/MacOS/Mozilla VPN</string>
                        <string>macosdaemon</string>
                </array>
                <key>UserName</key>
                <string>root</string>
                <key>RunAtLoad</key>
                <true/>
                <key>KeepAlive</key>
                <true/>
                <key>SoftResourceLimits</key>
                <dict>
                        <key>NumberOfFiles</key>
                        <integer>1024</integer>
                </dict>
                <key>StandardErrorPath</key>
                <string>$LOG_DIR/stderr.log</string>
        </dict>
</plist>
EOM
)

pkill -x "Mozilla VPN" || echo "Unable to kill GUI, not running?"
sleep 1

UPDATING=
if [ -f "$DAEMON_PLIST_PATH" ]; then
  UPDATING=1
fi

# Load the daemon
launchctl unload -w $DAEMON_PLIST_PATH
echo "$DAEMON_PLIST" > $DAEMON_PLIST_PATH
launchctl load -w $DAEMON_PLIST_PATH

if [ -f "/Applications/Mozilla VPN.app/Contents/Resources/utils/mozillavpn.json" ]; then
  # Install the firefox native messaging manifest
  mkdir -p "/Library/Application Support/Mozilla/NativeMessagingHosts"
  cp -f "/Applications/Mozilla VPN.app/Contents/Resources/utils/mozillavpn.json" "/Library/Application Support/Mozilla/NativeMessagingHosts/mozillavpn.json"

  # Install the chrome native messaging manifest
  mkdir -p "/Library/Google/Chrome/NativeMessagingHosts"
  cp -f "/Applications/Mozilla VPN.app/Contents/Resources/utils/mozillavpn.json" "/Library/Google/Chrome/NativeMessagingHosts/mozillavpn.json"

  # Install the chromium native messaging manifest
  mkdir -p "/Library/Application Support/Chromium/NativeMessagingHosts"
  cp -f "/Applications/Mozilla VPN.app/Contents/Resources/utils/mozillavpn.json" "/Library/Application Support/Chromium/NativeMessagingHosts/mozillavpn.json"
fi

# Run the app
if [ "$UPDATING" ]; then
  open -a "/Applications/Mozilla VPN.app" --args ui --updated
else
  open -a "/Applications/Mozilla VPN.app"
fi
exit 0
