#! /bin/bash

set -e

# Relaunch the app from the installed location after installation.
# Params:
# - PID - If given, kills this PID from a disowned subshell, and waits for it to
#   terminate before relaunching
# - ORIGAPP - Original app bundle path (typically in Downloads or the client
#   update directory) - if given, removes this path after relaunching (to avoid
#   extra copies of the app)
PID="$1"
ORIGAPP="$2"

appDir="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"

# If a PID was passed, kill our parent and relaunch
if [ -n "$PID" ] && [[ $PID =~ ^[0-9]+$ ]] ; then
    echo "Relaunching client"

    # Launch a disowned subshell
    (
        # Wait for parent process to die
        while kill -0 "$PID" 2> /dev/null ; do sleep 0.2 ; done
        # Launch new app as the logged in user (not root)

        # Try opening the app a number of times before giving up -
        # Big Sur sometimes fails to find the executable (with error: kLSNoExecutableErr)
        # on the first few attempts.
        for i in $(seq 1 10); do
          echo "attempt $i to open $appDir"
          if open "$appDir" --args "--clear-cache" ; then
            break
          fi
          sleep 0.2
        done

        # Remove the installer copy of the app
        if [ -n "$ORIGAPP" ]; then
          rm -rf "$ORIGAPP" || true
        fi

    ) & disown
else
    # Just launch directly
    open "$appDir" --args "--clear-cache"
    if [ -n "$ORIGAPP" ]; then
        rm -rf "$ORIGAPP" || true
    fi
fi
