#!/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.
#
# This script is part of the microsoft-edge package.
#
# It creates the repository configuration file for package updates, since
# we cannot do this during the microsoft-edge installation since the repository
# is locked.
#
# This functionality can be controlled by creating the $DEFAULTS_FILE and
# setting "repo_add_once" to "true" or "false" as desired. An empty
# $DEFAULTS_FILE is the same as setting the value to "false".

# System-wide package configuration.
DEFAULTS_FILE="/etc/default/microsoft-edge"

# Microsoft-specific packaging changes
ms_key_url=https://packages.microsoft.com/keys/microsoft.asc
ms_key_hash=EB3E94ADBE1229CF
# rpm-only
ms_key_package=gpg-pubkey-be1229cf-5631588c

# PUMP: DO NOT MERGE UPSTREAM CHANGES

# sources.list setting for microsoft-edge updates.
REPOCONFIG="https://packages.microsoft.com/yumrepos/edge/"
REPOCONFIGREGEX=""

# ms_key_* defined in variables.include

# Install the repository/package signing keys, if they aren't already.
# (see also: https://packages.microsoft.com/)
install_rpm_key() {
  KEY_PACKAGE="$ms_key_package"
  # Check to see if all keys already exists.
  # Make sure all the most recent signing subkeys are installed.
  MS_NEED_KEYS=0

  # https://packages.microsoft.com/keys/microsoft.asc
  rpm -q ${KEY_PACKAGE} --qf '%{Pubkeys:armor}\n' | \
    gpg --with-colons - 2>/dev/null | \
    grep -q $ms_key_hash
  if [ "$?" -ne "0" ]; then
    MS_NEED_KEYS=1
  fi

  if [ $MS_NEED_KEYS -ne 1 ]; then
    return
  fi

  # Make sure no older version of the key is installed because it appears
  # 'rpm --import' won't overwrite an existing key package.
  rpm -q ${KEY_PACKAGE} >/dev/null 2>&1
  if [ "$?" -eq "0" ]; then
    # Note, if this is run during the package install, it will fail because rpm
    # can't recursively run rpm, but it should work when run later as part of
    # the installed cron job (and probably nothing needs the new keys before
    # then).
    rpm -e --allmatches ${KEY_PACKAGE} >/dev/null 2>&1 || return
  fi

  if [ -n "$NEED_KEYS" ]; then
    echo "Error: NEED_KEYS, is set. Only MS_NEED_KEYS should be set."
    echo "This might be due to a bad merge."
    exit 1
  fi

  # Note for future merges: the PGP block below was intentionally
  # changed from a Google key to a Microsoft (packages.microsoft.com)
  # key.

  # RPM on Mandriva 2009 is dumb and does not understand "rpm --import -"
  TMPKEY=$(mktemp /tmp/microsoft.sig.XXXXXX)
  if [ -n "$TMPKEY" ]; then
    cat > "$TMPKEY" <<KEYDATA
-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG v1.4.7 (GNU/Linux)

mQENBFYxWIwBCADAKoZhZlJxGNGWzqV+1OG1xiQeoowKhssGAKvd+buXCGISZJwT
LXZqIcIiLP7pqdcZWtE9bSc7yBY2MalDp9Liu0KekywQ6VVX1T72NPf5Ev6x6DLV
7aVWsCzUAF+eb7DC9fPuFLEdxmOEYoPjzrQ7cCnSV4JQxAqhU4T6OjbvRazGl3ag
OeizPXmRljMtUUttHQZnRhtlzkmwIrUivbfFPD+fEoHJ1+uIdfOzZX8/oKHKLe2j
H632kvsNzJFlROVvGLYAk2WRcLu+RjjggixhwiB+Mu/A8Tf4V6b+YppS44q8EvVr
M+QvY7LNSOffSO6Slsy9oisGTdfE39nC7pVRABEBAAG0N01pY3Jvc29mdCAoUmVs
ZWFzZSBzaWduaW5nKSA8Z3Bnc2VjdXJpdHlAbWljcm9zb2Z0LmNvbT6JATUEEwEC
AB8FAlYxWIwCGwMGCwkIBwMCBBUCCAMDFgIBAh4BAheAAAoJEOs+lK2+EinPGpsH
/32vKy29Hg51H9dfFJMx0/a/F+5vKeCeVqimvyTM04C+XENNuSbYZ3eRPHGHFLqe
MNGxsfb7C7ZxEeW7J/vSzRgHxm7ZvESisUYRFq2sgkJ+HFERNrqfci45bdhmrUsy
7SWw9ybxdFOkuQoyKD3tBmiGfONQMlBaOMWdAsic965rvJsd5zYaZZFI1UwTkFXV
KJt3bp3Ngn1vEYXwijGTa+FXz6GLHueJwF0I7ug34DgUkAFvAs8Hacr2DRYxL5RJ
XdNgj4Jd2/g6T9InmWT0hASljur+dJnzNiNCkbn9KbX7J/qK1IbR8y560yRmFsU+
NdCFTW7wY0Fb1fWJ+/KTsC4=
=J6gs
-----END PGP PUBLIC KEY BLOCK-----
KEYDATA
    rpm --import "$TMPKEY"
    rc=$?
    rm -f "$TMPKEY"
    if [ "$rc" -eq "0" ]; then
      return 0
    fi
  fi
  return 1
}

determine_rpm_package_manager() {
  local RELEASE

  # Modern method using os-release(5)
  if [ -f "/etc/os-release" ]; then
    RELEASE=$(. "/etc/os-release"; echo "$ID")
    case $RELEASE in
    "fedora"|"rhel"|"centos"|"amzn"|"mageia"|"openmandriva")
      PACKAGEMANAGERS=(yum)
      ;;
    "suse"|"sles"|"sled"|"opensuse"|"opensuse-leap"|"opensuse-tumbleweed")
      PACKAGEMANAGERS=(zypp)
      ;;
    esac
  fi

  if [ "$PACKAGEMANAGERS" ]; then
    return
  fi

  # Fallback method using lsb_release(1)
  LSB_RELEASE="$(command -v lsb_release 2> /dev/null)"
  if [ -x "$LSB_RELEASE" ]; then
    RELEASE=$(lsb_release -i 2> /dev/null | sed 's/:\t/:/' | cut -d ':' -f 2-)
    case $RELEASE in
    "Fedora"|"Amazon"|"Mageia"|"OpenMandrivaLinux")
      PACKAGEMANAGERS=(yum)
      ;;
    "SUSE LINUX"|"openSUSE")
      PACKAGEMANAGERS=(zypp)
      ;;
    esac
  fi

  if [ "$PACKAGEMANAGERS" ]; then
    return
  fi

  # Fallback methods that are probably unnecessary on modern systems.
  if [ -f "/etc/fedora-release" ] || [ -f "/etc/redhat-release" ]; then
    PACKAGEMANAGERS=(yum)
  elif [ -f "/etc/system-release" ] && grep -Fq "Amazon Linux" "/etc/system-release"; then
    PACKAGEMANAGERS=(yum)
  elif [ -f "/etc/SuSE-release" ]; then
    PACKAGEMANAGERS=(zypp)
  fi
}

DEFAULT_ARCH="x86_64"
YUM_REPO_FILE="/etc/yum.repos.d/microsoft-edge.repo"
ZYPPER_REPO_FILE="/etc/zypp/repos.d/microsoft-edge.repo"

install_yum() {
  install_rpm_key

  if [ ! "$REPOCONFIG" ]; then
    return 0
  fi

  if [ -d "/etc/yum.repos.d" ]; then
cat > "$YUM_REPO_FILE" << REPOCONTENT
[microsoft-edge]
name=microsoft-edge
baseurl=$REPOCONFIG
enabled=1
gpgcheck=1
gpgkey=$ms_key_url
REPOCONTENT
  fi
}

install_zypp() {
  if [ ! "$REPOCONFIG" ]; then
    return 0
  fi

  # Ideally, we would run: zypper addrepo -t YUM -f \
  # "$REPOCONFIG/$DEFAULT_ARCH" "microsoft-edge"
  # but that does not work when zypper is running.
  if [ -d "/etc/zypp/repos.d" ]; then
cat > "$ZYPPER_REPO_FILE" << REPOCONTENT
[microsoft-edge]
name=microsoft-edge
enabled=1
autorefresh=1
baseurl=$REPOCONFIG
gpgcheck=1
gpgkey=https://dl.google.com/linux/linux_signing_key.pub
type=rpm-md
keeppackages=0
REPOCONTENT
  fi
}

# Check if the automatic repository configuration is done, so we know when to
# stop trying.
verify_install() {
  # It's probably enough to see that the repo configs have been created. If they
  # aren't configured properly, update_bad_repo should catch that when it's run.
  case $1 in
  "yum")
    [ -f "$YUM_REPO_FILE" ]
    ;;
  "zypp")
    [ -f "$ZYPPER_REPO_FILE" ]
    ;;
  esac
}

# Update the Microsoft repository if it's not set correctly.
update_bad_repo() {
  if [ ! "$REPOCONFIG" ]; then
    return 0
  fi

  determine_rpm_package_manager

  for PACKAGEMANAGER in ${PACKAGEMANAGERS[*]}
  do
    case $PACKAGEMANAGER in
    "yum")
      update_repo_file "$YUM_REPO_FILE"
      ;;
    "zypp")
      update_repo_file "$ZYPPER_REPO_FILE"
      ;;
    esac
  done
}

update_repo_file() {
  REPO_FILE="$1"

  # Don't do anything if the file isn't there, since that probably means the
  # user disabled it.
  if [ ! -r "$REPO_FILE" ]; then
    return 0
  fi

  # Check if the correct repository configuration is in there.
  REPOMATCH=$(grep "^baseurl=$REPOCONFIG" "$REPO_FILE" \
    2>/dev/null)
  # If it's there, nothing to do
  if [ "$REPOMATCH" ]; then
    return 0
  fi

  # Check if it's there but disabled by commenting out (as opposed to using the
  # 'enabled' setting).
  MATCH_DISABLED=$(grep "^[[:space:]]*#.*baseurl=$REPOCONFIG" \
    "$REPO_FILE" 2>/dev/null)
  if [ "$MATCH_DISABLED" ]; then
    # It's OK for it to be disabled, as long as nothing bogus is enabled in its
    # place.
    ACTIVECONFIGS=$(grep "^baseurl=.*" "$REPO_FILE" 2>/dev/null)
    if [ ! "$ACTIVECONFIGS" ]; then
      return 0
    fi
  fi

  # If we get here, the correct repository wasn't found, or something else is
  # active, so fix it. This assumes there is a 'baseurl' setting, but if not,
  # then that's just another way of disabling, so we won't try to add it.
  sed -i -e "s,^baseurl=.*,baseurl=$REPOCONFIG," "$REPO_FILE"
}

# We only remove the repository configuration during a purge. Since RPM has
# no equivalent to dpkg --purge, the code below is actually never used. We
# keep it only for reference purposes, should we ever need it.
#
#remove_yum() {
#  rm -f "$YUM_REPO_FILE"
#}
#
#remove_zypp() {
#  # Ideally, we would run: zypper removerepo "microsoft-edge"
#  # but that does not work when zypper is running.
#  rm -f /etc/zypp/repos.d/microsoft-edge.repo
#}

DEFAULT_ARCH="x86_64"

get_lib_dir() {
  if [ "$DEFAULT_ARCH" = "i386" ] || [ "$DEFAULT_ARCH" = "armhf" ] || \
      [ "$DEFAULT_ARCH" = "mipsel" ]; then
    LIBDIR=lib
  elif [ "$DEFAULT_ARCH" = "x86_64" ] || [ "$DEFAULT_ARCH" = "aarch64" ] || \
        [ "$DEFAULT_ARCH" = "mips64el" ]; then
    LIBDIR=lib64
  else
    echo Unknown CPU Architecture: "$DEFAULT_ARCH"
    exit 1
  fi
}

## MAIN ##
if [ -r "$DEFAULTS_FILE" ]; then
  . "$DEFAULTS_FILE"
fi

install_rpm_key

if [ "$repo_add_once" = "true" ]; then
  determine_rpm_package_manager

  # Let's run through this for each supported package manager as detected...
  for PACKAGEMANAGER in ${PACKAGEMANAGERS[*]}
  do
    # The initial install happens in the post-install scripts, but there have been
    # reports of configuration problems, so just verify that everything looks
    # good, and if not, try to install again.
    verify_install $PACKAGEMANAGER
    if [ $? -ne 0 ]; then
      install_${PACKAGEMANAGER}
    fi
  done

  if [ $? -eq 0 ]; then
    # Do this for each supported package manager...
    for PACKAGEMANAGER in ${PACKAGEMANAGERS[*]}
    do
      # Before we quit auto-configuration, check that everything looks sane, since
      # part of this happened during package install and we don't have the return
      # value of that process.
      verify_install $PACKAGEMANAGER
      if [ $? -eq 0 ]; then
        sed -i -e 's/[[:space:]]*repo_add_once=.*/repo_add_once="false"/' \
          "$DEFAULTS_FILE"
      fi
    done
  fi
else
  update_bad_repo
fi
