#!/usr/bin/env bash

set -eux

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.
#
# TODO: 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
chmod 755 $LOG_DIR
exec > $LOG_DIR/preinstall.log 2>&1

echo "Running preinstall at $(date)"

# Stop the existing daemon
"$INSTALL_DIR/Mullvad VPN.app/Contents/Resources/mullvad-setup" prepare-restart &>/dev/null || \
    echo "Failed to send 'prepare-restart' command to old mullvad-daemon"

# NOTE: This path must be kept in sync with the path defined
# in mullvad-daemon/src/macos_launch_daemon.rs and postinstall
DAEMON_PLIST_PATH="/Library/LaunchDaemons/net.mullvad.daemon.plist"
launchctl unload -w $DAEMON_PLIST_PATH || echo "Failed to unload old mullvad-daemon"

# Migrate cache files from <=2020.8-beta2 paths
OLD_CACHE_DIR="/var/root/Library/Caches/mullvad-vpn"
NEW_CACHE_DIR="/Library/Caches/mullvad-vpn"

if [ -d "$OLD_CACHE_DIR" ]; then
    echo "Found old cache dir at $OLD_CACHE_DIR, moving to $NEW_CACHE_DIR"
    mkdir -p "$NEW_CACHE_DIR"
    mv "$OLD_CACHE_DIR"/* "$NEW_CACHE_DIR/" || echo "Unable to migrate cache. No cache files?"
    rm -rf "$OLD_CACHE_DIR"
fi

# Remove the existing relay and API address cache lists.
# There is a risk that they're incompatible with the format this version wants
rm "$NEW_CACHE_DIR/relays.json" || true
rm "$NEW_CACHE_DIR/api-ip-address.txt" || true

# Kill the GUI before proceeding with the upgrade.
pkill -x "Mullvad VPN" && sleep 1 || echo "Unable to kill GUI, not running?"
