#!/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
)

# Kill all the existing apps
pkill -x "Mozilla VPN" || echo "Unable to kill GUI, not running?"
sleep 1

# Installing the service
launchctl unload -w $DAEMON_PLIST_PATH
echo "$DAEMON_PLIST" > $DAEMON_PLIST_PATH
launchctl load -w $DAEMON_PLIST_PATH

# Running the app
open "/Applications/Mozilla VPN.app"
