#!/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, and it
# monitors that config to see if it has been disabled by the overly aggressive
# distro upgrade process (e.g.  intrepid -> jaunty). When this situation is
# detected, the respository will be re-enabled. If the respository is disabled
# for any other reason, this won't re-enable it.
#
# This functionality can be controlled by creating the $DEFAULTS_FILE and
# setting "repo_reenable_on_distupgrade" to "true" or "false" as desired.
# An empty $DEFAULTS_FILE is the same as setting it to "false".
#
# The $DEFAULTS_FILE also has a setting "repo_add_once" which can be set
# to "false" to prevent the package install from adding the repo altogether.

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

# sources.list setting for microsoft-edge updates.
REPOCONFIG="deb [arch=amd64] https://packages.microsoft.com/repos/edge stable main"
REPOCONFIGREGEX="deb (\[arch=[^]]*\bamd64\b[^]]*\][[:space:]]*) https?://packages.microsoft.com/repos/edge 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=1

# pub   rsa2048 2015-10-28 [SC]
#       BC528686B50D79E339D3721CEB3E94ADBE1229CF
# uid           [ unknown] Microsoft (Release signing) <gpgsecurity@microsoft.com>
PGP_KEY_DATA=$(cat <<KEYDATA
mQENBFYxWIwBCADAKoZhZlJxGNGWzqV+1OG1xiQeoowKhssGAKvd+buXCGISZJwT
LXZqIcIiLP7pqdcZWtE9bSc7yBY2MalDp9Liu0KekywQ6VVX1T72NPf5Ev6x6DLV
7aVWsCzUAF+eb7DC9fPuFLEdxmOEYoPjzrQ7cCnSV4JQxAqhU4T6OjbvRazGl3ag
OeizPXmRljMtUUttHQZnRhtlzkmwIrUivbfFPD+fEoHJ1+uIdfOzZX8/oKHKLe2j
H632kvsNzJFlROVvGLYAk2WRcLu+RjjggixhwiB+Mu/A8Tf4V6b+YppS44q8EvVr
M+QvY7LNSOffSO6Slsy9oisGTdfE39nC7pVRABEBAAG0N01pY3Jvc29mdCAoUmVs
ZWFzZSBzaWduaW5nKSA8Z3Bnc2VjdXJpdHlAbWljcm9zb2Z0LmNvbT6JATQEEwEI
AB4FAlYxWIwCGwMGCwkIBwMCAxUIAwMWAgECHgECF4AACgkQ6z6Urb4SKc+P9gf/
diY2900wvWEgV7iMgrtGzx79W/PbwWiOkKoD9sdzhARXWiP8Q5teL/t5TUH6TZ3B
ENboDjwr705jLLPwuEDtPI9jz4kvdT86JwwG6N8gnWM8Ldi56SdJEtXrzwtlB/Fe
6tyfMT1E/PrJfgALUG9MWTIJkc0GhRJoyPpGZ6YWSLGXnk4c0HltYKDFR7q4wtI8
4cBu4mjZHZbxIO6r8Cci+xxuJkpOTIpr4pdpQKpECM6x5SaT2gVnscbN0PE19KK9
nPsBxyK4wW0AvAhed2qldBPTipgzPhqB2gu0jSryil95bKrSmlYJd1Y1XfNHno5D
xfn5JwgySBIdWWvtOI05gw==
KEYDATA
)

PGP_KEY_CHECKSUM="=zPfd"

PGP_SUBKEYS=""

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

GPG_FILE="/usr/share/keyrings/microsoft-edge.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/microsoft-edge.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/microsoft-edge.gpg"
}

remove_legacy_list() {
  find_apt_sources
  LEGACY_LIST="$APT_SOURCESDIR/microsoft-edge.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: Microsoft Edge
Types: deb
URIs: https://packages.microsoft.com/repos/edge-stable
Suites: stable
Components: main
Architectures: amd64
Signed-By: $GPG_FILE
EOF
}

# Add the Microsoft 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/microsoft-edge.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
}

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

install_key

if [ "$repo_add_once" = "true" ]; then
  create_sources_lists
elif [ "$repo_reenable_on_distupgrade" = "true" ]; then
  install_deb822_sources
fi
