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

set -e

# System-wide package configuration.
DEFAULTS_FILE="/etc/default/google-chrome"

# Add icons to the system icons
XDG_ICON_RESOURCE="`command -v xdg-icon-resource 2> /dev/null || true`"
if [ ! -x "$XDG_ICON_RESOURCE" ]; then
  echo "Error: Could not find xdg-icon-resource" >&2
  exit 1
fi
for icon in  product_logo_16.png product_logo_24.png product_logo_32.png product_logo_48.png product_logo_64.png product_logo_128.png product_logo_256.png; do
  size="$(echo ${icon} | sed 's/[^0-9]//g')"
  "$XDG_ICON_RESOURCE" install --size "${size}" "/opt/google/chrome/${icon}" \
    "google-chrome"
done

# Update cache of .desktop file MIME types. Non-fatal since it's just a cache.
update-desktop-database > /dev/null 2>&1 || true

# Updates defaults.list file if present.
update_defaults_list() {
  # $1: name of the .desktop file

  local DEFAULTS_LIST="/usr/share/applications/defaults.list"

  if [ ! -f "${DEFAULTS_LIST}" ]; then
    return
  fi

  # Split key-value pair out of MimeType= line from the .desktop file,
  # then split semicolon-separated list of mime types (they should not contain
  # spaces).
  mime_types="$(grep MimeType= /usr/share/applications/${1} |
                cut -d '=' -f 2- |
                tr ';' ' ')"
  for mime_type in ${mime_types}; do
    if egrep -q "^${mime_type}=" "${DEFAULTS_LIST}"; then
      if ! egrep -q "^${mime_type}=.*${1}" "${DEFAULTS_LIST}"; then
        default_apps="$(grep ${mime_type}= "${DEFAULTS_LIST}" |
                        cut -d '=' -f 2-)"
        egrep -v "^${mime_type}=" "${DEFAULTS_LIST}" > "${DEFAULTS_LIST}.new"
        echo "${mime_type}=${default_apps};${1}" >> "${DEFAULTS_LIST}.new"
        mv "${DEFAULTS_LIST}.new" "${DEFAULTS_LIST}"
      fi
    else
      # If there's no mention of the mime type in the file, add it.
      echo "${mime_type}=${1};" >> "${DEFAULTS_LIST}"
    fi
  done
}

update_defaults_list "google-chrome.desktop"

# This function uses sed to insert the contents of one file into another file,
# after the first line matching a given regular expression. If there is no
# matching line, then the file is unchanged.
insert_after_first_match() {
  # $1: file to update
  # $2: regular expression
  # $3: file to insert
  sed -i -e "1,/$2/ {
    /$2/ r $3
    }" "$1"
}

# If /usr/share/gnome-control-center/default-apps/gnome-default-applications.xml
# exists, it may need to be updated to add ourselves to the default applications
# list. If we find the file and it does not seem to contain our patch already
# (the patch is safe to leave even after uninstall), update it.
GNOME_DFL_APPS=/usr/share/gnome-control-center/default-apps/gnome-default-applications.xml
if [ -f "$GNOME_DFL_APPS" ]; then
# Conditionally insert the contents of the file "default-app-block" after the
# first "<web-browsers>" line we find in gnome-default-applications.xml
  fgrep -q "Google Chrome" "$GNOME_DFL_APPS" || insert_after_first_match \
    "$GNOME_DFL_APPS" \
    "^[ 	]*<web-browsers>[ 	]*$" \
    "/opt/google/chrome/default-app-block"
fi

# This function performs the setup for the chrome management service process.
# It creates a new chromemgmt group, creates the signing key file, and updates
# permissions for both the signing key file and the binary.
chrome_management_service_setup() {
  if [ ! -f "$DEFAULTS_FILE" ]; then
    return
  fi

  if ! grep -q "install_device_trust_key_management_command=true" \
    "$DEFAULTS_FILE"; then
    return
  fi

  getent group chromemgmt > /dev/null || groupadd chromemgmt

  chgrp chromemgmt "/opt/google/chrome/chrome-management-service"
  chmod 2755 "/opt/google/chrome/chrome-management-service"

  mkdir -p "/etc/opt/chrome/policies/enrollment"
  SIGNING_KEY_FILE="/etc/opt/chrome/policies/enrollment/DeviceTrustSigningKey"
  if [ ! -e "$SIGNING_KEY_FILE" ]; then
    touch "$SIGNING_KEY_FILE"
  fi

  chgrp chromemgmt "$SIGNING_KEY_FILE"
  chmod 664 "$SIGNING_KEY_FILE"
}

chrome_management_service_setup

# Add to the alternatives system
#
# On Ubuntu 12.04, we have the following priorities
# (which can be obtain be installing browsers and running
# update-alternatives --query x-www-browser):
#
# /usr/bin/epiphany-browser  85
# /usr/bin/firefox           40
# /usr/bin/konqueror         30
#
# While we would expect these values to be keyed off the most popular
# browser (Firefox), in practice, we treat Epiphany as the lower bound,
# resulting in the following scheme:

CHANNEL=stable
case $CHANNEL in
  stable )
    # Good enough to be the default.
    PRIORITY=200
    ;;
  beta )
    # Almost good enough to be the default. (Firefox stable should arguably be
    # higher than this, but since that's below the "Epiphany threshold", we're
    # not setting our priority below it. Anyone want to poke Firefox to raise
    # their priority?)
    PRIORITY=150
    ;;
  unstable )
    # Unstable, give it the "lowest" priority.
    PRIORITY=120
    ;;
  * )
    PRIORITY=0
    ;;
esac

update-alternatives --install /usr/bin/x-www-browser x-www-browser \
  /usr/bin/google-chrome-stable $PRIORITY
update-alternatives --install /usr/bin/gnome-www-browser gnome-www-browser \
  /usr/bin/google-chrome-stable $PRIORITY

update-alternatives --install /usr/bin/google-chrome google-chrome \
  /usr/bin/google-chrome-stable $PRIORITY

# sources.list setting for google-chrome updates.
REPOCONFIG="deb [arch=amd64] https://dl.google.com/linux/chrome/deb/ stable main"
REPOCONFIGREGEX="deb (\[arch=[^]]*\bamd64\b[^]]*\][[:space:]]*) https?://dl.google.com/linux/chrome/deb/ stable main"
# This file is automatically generated by update_key_include.py
# Do not edit this file directly.

# This is used as a priority value for the key file, so newer
# keyrings should always take priority.
PGP_KEY_VERSION=2

# pub   rsa4096 2016-04-12 [SC]
#       EB4C1BFD4F042F6DDDCCEC917721F63BD38B4796
# uid           [ unknown] Google Inc. (Linux Packages Signing Authority) <linux-packages-keymaster@google.com>
# sub   rsa4096 2024-01-30 [S] [expires: 2027-01-29]
# sub   rsa4096 2025-01-07 [S] [expires: 2028-01-07]
PGP_KEY_DATA=$(cat <<KEYDATA
mQINBFcMjNMBEAC6Wr5QuLIFgz1V1EFPlg8ty2TsjQEl4VWftUAqWlMevJFWvYEx
BOsOZ6kNFfBfjAxgJNWTkxZrHzDl74R7KW/nUx6X57bpFjUyRaB8F3/NpWKSeIGS
pJT+0m2SgUNhLAn1WY/iNJGNaMl7lgUnaP+/ZsSNT9hyTBiH3Ev5VvAtMGhVI/u8
P0EtTjXp4o2U+VqFTBG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Y0v
Ea4G+n6WT3DwEan6plZ3/xM6s4caZfP43ZZkEiu1M1svQtgzF98HFxAhX5oLyMPw
x8R61X0XtKxmjVbNrTBwRfJf/FRDmmv5qSxoO2g1gpbCcm2VGoGBvoDws95GvPFN
lWUes4xQMclIo01JuynJGLyOaEm19TXu4T36ulCTO/b1lGIOLi+25vpFKlwBrD6y
q4yrt81t6vGvtI1pZrt1Wcm7hce8CFLrzfzo2D28yHPIsT0YvK7AnwUK/SMKIV1E
UNrLIRhnTMBnP+BaOF0HxcAYnlRLSwScPx2pATglHmIvNcRkCsfIZQOXjn8lvFXs
7lnkP5KUF5/+ccsJj8kEdzcsYaczQe3wY2N36ibqRPOfPeVmPFAKPQsUdgx47cAP
KTm6PxIp73IxceGXbkOXJ7W1lqVPKiwQh09RkwWpMtJA2HSdbmInxBiE71tJqSxQ
pp2EfNXOgWTTrs46lkuW39I7dr0NOAGomeaNnOuexMmlTZy2Rf77BfozRZIZ+RAY
lZu5/W1Ed2X4iR8i76QET6ICFmgxADKzB4WnpeBaBqAr
KEYDATA
)

PGP_KEY_CHECKSUM="=AcRC"

PGP_SUBKEYS="32EE5355A6BC6E42 FD533C07C264648F"

APT_CONFIG="$(command -v apt-config 2>/dev/null)"

GPG_FILE="/usr/share/keyrings/google-chrome.gpg"

# Set variables for the locations of the apt trusted keyrings.
find_apt_trusted() {
  eval $("$APT_CONFIG" shell APT_TRUSTEDDIR 'Dir::Etc::trustedparts/d')
}

# Set variables for the locations of the apt sources lists.
find_apt_sources() {
  eval $("$APT_CONFIG" shell APT_SOURCESDIR 'Dir::Etc::sourceparts/d')
  SOURCES_FILE="$APT_SOURCESDIR/google-chrome.sources"
}

# Install the repository/package signing keys. The key cannot be part of the
# package since it's still needed if the package is removed but not purged.
install_key() {
  if [ ! -e /usr/share/keyrings ]; then
    mkdir -p /usr/share/keyrings
    chmod 755 /usr/share/keyrings
  fi

  # Use a temporary file to ensure atomic updates
  echo "$PGP_KEY_DATA" | base64 -d >"$GPG_FILE.$$.tmp"
  chmod 644 "$GPG_FILE.$$.tmp"
  mv "$GPG_FILE.$$.tmp" "$GPG_FILE"
}

uninstall_key() {
  rm -f "$GPG_FILE"
}

remove_legacy_key() {
  find_apt_trusted
  rm -f "$APT_TRUSTEDDIR/google-chrome.gpg"
}

remove_legacy_list() {
  find_apt_sources
  LEGACY_LIST="$APT_SOURCESDIR/google-chrome.list"
  if [ ! -f "$LEGACY_LIST" ]; then
    return
  fi

  # Check for other sources (strict check for 'ours')
  # If there are any lines starting with 'deb' (commented or not) that do NOT
  # match our strict regex, keep the file.
  if grep -E "^[[:space:]]*#?[[:space:]]*deb" "$LEGACY_LIST" |
    grep -v -E \
    "^[[:space:]]*#?[[:space:]]*$REPOCONFIGREGEX" >/dev/null;
  then
    # Other sources exist, comment out ours (strict match)
    sed -i -E "s|^[[:space:]]*($REPOCONFIGREGEX)|# \1|" "$LEGACY_LIST"
  else
    # No other sources, safe to remove
    rm -f "$LEGACY_LIST"
  fi
}

# Generate the content of the .sources file
gen_sources_content() {
  cat <<EOF
### THIS FILE IS AUTOMATICALLY CONFIGURED ###
# Changes to this file will not be preserved.
# This file will not be recreated if removed.
X-Repolib-Name: Google Chrome
Types: deb
URIs: https://dl.google.com/linux/chrome-stable/deb/
Suites: stable
Components: main
Signed-By: $GPG_FILE
EOF
}

# Add the Google repository to the apt sources. The sources cannot be part of
# the package since it's still needed if the package is removed but not purged.
create_sources_lists() {
  find_apt_sources

  gen_sources_content >"$SOURCES_FILE.$$.tmp"
  chmod 644 "$SOURCES_FILE.$$.tmp"
  mv "$SOURCES_FILE.$$.tmp" "$SOURCES_FILE"

  if [ -r "$DEFAULTS_FILE" ]; then
    if grep -q "^[[:space:]]*repo_add_once=" "$DEFAULTS_FILE"; then
      sed -i -e \
        's/^[[:space:]]*repo_add_once=.*/repo_add_once="false"/' \
        "$DEFAULTS_FILE"
    else
      echo 'repo_add_once="false"' >>"$DEFAULTS_FILE"
    fi
  fi
}

# Remove our custom sources file.
clean_sources_lists() {
  find_apt_sources
  rm -f "$SOURCES_FILE"
}

install_deb822_sources() {
  find_apt_sources
  LEGACY_LIST="$APT_SOURCESDIR/google-chrome.list"

  SHOULD_INSTALL_SOURCES=0
  # Detect new installs.
  if [ -r "$DEFAULTS_FILE" ]; then
    if grep -E -q \
      '^[[:space:]]*repo_add_once=[[:space:]]*["'\'']?true["'\'']?' \
      "$DEFAULTS_FILE"; then
      SHOULD_INSTALL_SOURCES=1
    fi
  else
    SHOULD_INSTALL_SOURCES=1
    echo 'repo_add_once="true"' >"$DEFAULTS_FILE"
    echo 'repo_reenable_on_distupgrade="true"' >>"$DEFAULTS_FILE"
  fi

  if [ -f "$SOURCES_FILE" ]; then
    # The new .sources file already exists. Recreate it in case it got disabled
    # during a dist upgrade.
    SHOULD_INSTALL_SOURCES=1
  elif [ -f "$LEGACY_LIST" ]; then
    # Migrate a legacy .list file to the new .sources format.
    if grep -E -q "^[[:space:]]*$REPOCONFIGREGEX" "$LEGACY_LIST"; then
      SHOULD_INSTALL_SOURCES=1
    elif grep -E -q \
      "^[[:space:]]*#[[:space:]]*$REPOCONFIGREGEX[[:space:]]*# disabled on \
upgrade to .*" \
      "$LEGACY_LIST"; then
      SHOULD_INSTALL_SOURCES=1
    fi
  fi

  if [ "$SHOULD_INSTALL_SOURCES" -eq 1 ]; then
    create_sources_lists
  fi
}

NSS_FILES="libnspr4.so.0d libplds4.so.0d libplc4.so.0d libssl3.so.1d \
    libnss3.so.1d libsmime3.so.1d libnssutil3.so.1d"

add_nss_symlinks() {
  get_lib_dir
  for f in $NSS_FILES
  do
    target=$(echo $f | sed 's/\.[01]d$//')
    if [ -f "/$LIBDIR/$target" ]; then
      ln -snf "/$LIBDIR/$target" "/opt/google/chrome/$f"
    elif [ -f "/usr/$LIBDIR/$target" ]; then
      ln -snf "/usr/$LIBDIR/$target" "/opt/google/chrome/$f"
    else
      echo $f not found in "/$LIBDIR/$target" or "/usr/$LIBDIR/$target".
      exit 1
    fi
  done
}

remove_nss_symlinks() {
  for f in $NSS_FILES
  do
    rm -rf "/opt/google/chrome/$f"
  done
}

remove_udev_symlinks() {
  rm -rf "/opt/google/chrome/libudev.so.0"
}

remove_udev_symlinks

## MAIN ##
install_key
install_deb822_sources
# TODO(thomasanderson): Enable removal of legacy repo files once the new format
# is verified in the wild.
# remove_legacy_list
# remove_legacy_key
