#!/usr/bin/env bash

RUNNING_MARKER_FILE="/tmp/coder_desktop_running"
VPN_MARKER_FILE="/tmp/coder_vpn_was_running"

# Before this script, or the user, opens the app, make sure
# Gatekeeper has ingested the notarization ticket.
spctl -avvv "/Applications/Coder Desktop.app"
# spctl can't assess non-apps, so this will always return a non-zero exit code, 
# but the error message implies at minimum the signature of the extension was 
# checked. 
spctl -avvv "/Applications/Coder Desktop.app/Contents/Library/SystemExtensions/com.coder.Coder-Desktop.VPN.systemextension" || true

# Restart Coder Desktop if it was running before
if [ -f "$RUNNING_MARKER_FILE" ]; then
  echo "Starting Coder Desktop..."
  open -a "Coder Desktop"
  rm "$RUNNING_MARKER_FILE"
  echo "Coder Desktop started."
fi

# Restart VPN if it was running before
if [ -f "$VPN_MARKER_FILE" ]; then
  echo "Restarting CoderVPN..."
  echo "Sleeping for 3..."
  sleep 3
  scutil --nc start "Coder"
  rm "$VPN_MARKER_FILE"
  echo "CoderVPN started."
fi

exit 0
