#!/bin/sh
# This postinstall script is run on macOS pkg installers

# Extract a referral / promo code from the installer path of the format /dir/path/Setup-Brave-Anything-xxx001.pkg
# where the promo code would be xxx001
installerPath=$1
installationPath=$2
# TODO: ugly to assume the name of the app, especially with multi-channel.
# Luckily for now, release channel is the only channel with a pkg installer.
installationAppPath="$installationPath/Brave.app"
installerPathPromoCodeRegex='.+-(([a-zA-Z0-9]{3}[0-9]{3})|([a-zA-Z]{1,}-[a-zA-Z]{1,}))([[:blank:]]?\([0-9]+\))?\.pkg$'
userDataDir="$HOME/Library/Application Support/brave"
promoCodePath="$userDataDir/promoCode"
# pkg runs this script as root so we need to get current username
userName="$USER"
echo "Installer path is: $installerPath"
echo "Username is: $userName"
echo "Installation app path is: $installationAppPath"

# Fix the permissions on installed .app so that updater has permissions to write new contents.
# By default pkg with install the .app with root:wheel owner and 'drwxr-xr-x' permission.
# Since the app is run by the user, and the updater built-in to electron does not successfully
# escalate to root permissions, updating will fail.
# We'll allow all admin users of the machine permissions to update the app, as well as the installing-user
# (who may not be an admin).
sudo chmod -R 775 "$installationAppPath"
sudo chown -R $USER "$installationAppPath"
sudo chgrp -R admin "$installationAppPath"

# Detect if installer contained a referral promotion code within the filename
if [[ $installerPath =~ $installerPathPromoCodeRegex ]]; then
  echo "Installer path matched for promo code"
  n=${#BASH_REMATCH[*]}
  if [ $n -ge 1 ]; then
    promoCode=${BASH_REMATCH[1]}
    echo "Got promo code: $promoCode"
    echo "Writing to user data directory at: $userDataDir/promoCode"
    # TODO: it is a bit ugly to assume the user-data path here, and to manually
    # write to it and hopefully set the correct permissions. An alternative would
    # be to run Brave with a flag, similar to the process for Windows.
    mkdir -p "$userDataDir"
    echo "$promoCode" > "$promoCodePath"
    # fix permissions
    sudo chown "$userName" "$userDataDir"
    sudo chown "$userName" "$promoCodePath"
  fi
else
  echo "Installer path did not match for promo code"
fi

exit 0
