#!/usr/bin/env bash

set -eu

INSTALL_DIR=$2

# Workaround for issue in electron-builder where the pkg-scripts are run twice, once with the
# correct install dir and once with an incorrect one. This guard prevents running the script when
# called the second time. This can be reverted when the following issue has been fixed:
# https://github.com/electron-userland/electron-builder/issues/8166
if [[ $INSTALL_DIR == *"Mullvad VPN.app" ]]; then
    exit 0
fi

LOG_DIR=/var/log/mullvad-vpn

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

echo "Running postinstall at $(date)"

# Abort if the "localized" directory exists. This can happen if some other app bundle
# is already occupying the intended target directory, causing macOS to install us in
# /Applications/Mullvad VPN.localized instead. We abort in this case to avoid a potential
# LPE from admin user to root.
if [[ -d "$INSTALL_DIR/Mullvad VPN.localized" ]]; then
    echo "Found '$INSTALL_DIR/Mullvad VPN.localized' unexpectedly. Aborting."
    rm -rf "$INSTALL_DIR/Mullvad VPN.localized" || echo "Failed to remove '$INSTALL_DIR/Mullvad VPN.localized'"
    exit 1
fi
# Check if Mullvad VPN.app is owned by root. If not, non-root users may potentially overwrite
# application bundle contents, replace binaries etc., opening up the possibility of an LPE.
if [[ "$(stat -f %u "$INSTALL_DIR/Mullvad VPN.app")" -ne 0 ]]; then
    echo "Unexpected owner for '$INSTALL_DIR/Mullvad VPN.app' (not root). Aborting"
    exit 1
fi

# NOTE: This path must be kept in sync with the path defined
# in mullvad-daemon/src/macos_launch_daemon.rs and preinstall
DAEMON_PLIST_PATH="/Library/LaunchDaemons/net.mullvad.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>net.mullvad.daemon</string>

                <key>ProgramArguments</key>
                <array>
                        <string>$INSTALL_DIR/Mullvad VPN.app/Contents/Resources/mullvad-daemon</string>
                        <string>-vv</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>AssociatedBundleIdentifiers</key>
                <string>net.mullvad.vpn</string>

                <key>StandardErrorPath</key>
                <string>$LOG_DIR/stderr.log</string>
        </dict>
</plist>
EOM
)

ZSH_COMPLETIONS_DIR="/usr/local/share/zsh/site-functions/"

if [[ -d "/opt/homebrew/share/fish/vendor_completions.d/" ]]; then
    FISH_COMPLETIONS_DIR="/opt/homebrew/share/fish/vendor_completions.d/"
else
    FISH_COMPLETIONS_DIR="/usr/local/share/fish/vendor_completions.d/"
fi

cp "$LOG_DIR/daemon.log" "$LOG_DIR/old-install-daemon.log" \
  || echo "Failed to copy old daemon log"

# For compatibility with versions older than 2022.5, kill the GUI after the
# upgrade. We now do this in preinstall instead. This code can be removed when
# we drop support for app versions older than 2022.5.
pkill -x "Mullvad VPN" || true
sleep 1

echo "$DAEMON_PLIST" > $DAEMON_PLIST_PATH
chmod 644 $DAEMON_PLIST_PATH
launchctl load -w $DAEMON_PLIST_PATH

mkdir -p /usr/local/bin
ln -sf "$INSTALL_DIR/Mullvad VPN.app/Contents/Resources/mullvad" /usr/local/bin/mullvad
ln -sf "$INSTALL_DIR/Mullvad VPN.app/Contents/Resources/mullvad-problem-report" /usr/local/bin/mullvad-problem-report

mkdir -p "$ZSH_COMPLETIONS_DIR"
ln -sf "$INSTALL_DIR/Mullvad VPN.app/Contents/Resources/_mullvad" "$ZSH_COMPLETIONS_DIR/_mullvad"

if [[ -d "$FISH_COMPLETIONS_DIR" ]]; then
    ln -sf "$INSTALL_DIR/Mullvad VPN.app/Contents/Resources/mullvad.fish" "$FISH_COMPLETIONS_DIR/mullvad.fish"
fi

# Relaunch the GUI if it was running before the upgrade.
GUI_RUNNING_MARKER="/var/run/mullvad-gui-was-running"
if [[ -f "$GUI_RUNNING_MARKER" ]]; then
    rm -f "$GUI_RUNNING_MARKER"

    # Identify the console user. $USER is not trustworthy as it may be root if `sudo installer` is used.
    CONSOLE_USER=$(stat -f "%Su" /dev/console)
    if [[ -n "$CONSOLE_USER" && "$CONSOLE_USER" != "root" && "$CONSOLE_USER" != "loginwindow" ]]; then
        CONSOLE_UID=$(id -u "$CONSOLE_USER")
        launchctl asuser "$CONSOLE_UID" sudo -u "$CONSOLE_USER" \
            open -a "$INSTALL_DIR/Mullvad VPN.app" \
            || echo "Failed to relaunch GUI as $CONSOLE_USER"
    else
        echo "No console user; skipping GUI relaunch"
    fi
fi
