@SHEBANG_GUARD@#!/bin/bash -p

# Copyright 2019 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

set -eu

# The parameters to a pkg postinstall script are not well documented, so for the
# reader's clarification:
#
# $1 is the top-level package path
# $2 is the target (installation) location
# $3 is the target (installation) volume
# $4 is the startup disk root
readonly INSTALLATION_PATH=${2}

readonly APP_DIR="@APP_DIR@"
readonly APP_PRODUCT="@APP_PRODUCT@"
readonly BRAND_CODE="@BRAND_CODE@"
readonly FRAMEWORK_DIR="@FRAMEWORK_DIR@"

# Uses "defaults read" to obtain the value of a key in a property list.
#
# See chrome/installer/mac/keystone_install.sh for more details.
infoplist_read() {
  __CFPREFERENCES_AVOID_DAEMON=1 defaults read "${@}"
}

# 1. Install GoogleUpdater.

echo "Installing GoogleUpdater."

"${INSTALLATION_PATH}/${FRAMEWORK_DIR}/Helpers/GoogleUpdater.app/Contents/MacOS/GoogleUpdater" "--install" "--system"


# 2. If specified, create the brand file if it does not yet exist.

brand_file_written="false"
readonly BRAND_PLIST="/Library/Google/${APP_PRODUCT} Brand.plist"

if [[ -n "${BRAND_CODE}" ]] && [[ ! -f "${BRAND_PLIST}" ]]; then
  echo "Creating the brand file."

  readonly KS_BRAND_KEY="KSBrandID"

  # Failure to write a brand file is less important than getting automatic
  # updates configured.
  defaults write "${BRAND_PLIST}" "${KS_BRAND_KEY}" \
                 -string "${BRAND_CODE}" \
    && chmod 644 "${BRAND_PLIST}" \
    && brand_file_written="true"
else
  echo "Skipping the brand file."
fi

# 3. Register Chrome with GoogleUpdater via its ksadmin shim.

echo "Registering Chrome with GoogleUpdater."

readonly CHROME_APP_LOCATION="${INSTALLATION_PATH}/${APP_DIR}"
readonly CHROME_APP_INFO_PLIST="${CHROME_APP_LOCATION}/Contents/Info.plist"
readonly KS_VERSION_KEY="KSVersion"
readonly KS_PRODUCT_KEY="KSProductID"
readonly KS_URL_KEY="KSUpdateURL"
readonly KS_CHANNEL_KEY="KSChannelID"
readonly KS_ADMIN="/Library/Google/GoogleSoftwareUpdate/GoogleSoftwareUpdate.bundle/Contents/MacOS/ksadmin"

product="$(infoplist_read "${CHROME_APP_INFO_PLIST}" \
                          "${KS_PRODUCT_KEY}")"
version="$(infoplist_read "${CHROME_APP_INFO_PLIST}" \
                          "${KS_VERSION_KEY}")"

ksadmin_args=(
  --register
  --productid "${product}"
  --version "${version}"
  --xcpath "${CHROME_APP_LOCATION}"
  --tag-path "${CHROME_APP_INFO_PLIST}"
  --tag-key "${KS_CHANNEL_KEY}"
  --version-path "${CHROME_APP_INFO_PLIST}"
  --version-key "${KS_VERSION_KEY}"
)

if channel="$(infoplist_read "${CHROME_APP_INFO_PLIST}" \
                             "${KS_CHANNEL_KEY}")"; then
  ksadmin_args+=(
    --tag "${channel}"
  )
fi

if [[ "${brand_file_written}" == "true" ]]; then
  ksadmin_args+=(
    --brand-path "${BRAND_PLIST}"
    --brand-key "${KS_BRAND_KEY}"
  )
fi

"${KS_ADMIN}" "${ksadmin_args[@]}"
