#!/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 vivaldi 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_add_once" and/or "repo_reenable_on_distupgrade" to "true" or
# "false" as desired. An empty $DEFAULTS_FILE is the same as setting both values
# to "false".

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

# sources.list setting for vivaldi updates.
REPOCONFIG="deb [arch=amd64] https://repo.vivaldi.com/stable/deb/ stable main"
REPOCONFIGREGEX="deb (\[arch=[^]]*\bamd64\b[^]]*\][[:space:]]*) https?://repo.vivaldi.com/stable/deb/ stable main"

APT_GET="`command -v apt-get 2> /dev/null`"
APT_CONFIG="`command -v apt-config 2> /dev/null`"

SOURCES_PREAMBLE="### THIS FILE IS AUTOMATICALLY CONFIGURED ###
# You may comment out this entry, but any other modifications may be lost.\n"

# import Vivaldi public key updates from Vivaldi repo
# Vivaldi public key updates

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

# Install the repository/package signing key (33EAAB8E), if it isn't already.
install_key() {
  find_apt_trusted
  # ASCII-armored keyrings are only supported in apt 1.4 and later, but we must
  # continue supporting Trusty and Xenial which have older versions of apt, so
  # the keyring is installed as a binary blob.  base64 is used to decode the
  # ASCII keyring, which should always be available since it comes from the
  # coreutils.
  (base64 -d > "$APT_TRUSTEDDIR/vivaldi-33EAAB8E.gpg") <<KEYDATA
mQINBGO9ZysBEACeLmXsTfEk6Msqskhkr+fU2uFTinefc6o8p1T9uRVkBiIM641/
n76LtmGuGQkIsDi+a6XkdNE08hn8IHru3Ir5m2/oku8lP99U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njljpzjPvdpjSsCQ753IyqudXQ1aVscfrr
I31OB1JVAjCyziBpGVyNlOjVpYukWLoReQARAQABiQI8BBgBCgAmFiEEM2AY8mP6
AABlztfGEk8UmDPqq44FAmO9ZysCGwwFCQQEUgAACgkQEk8UmDPqq44Jkg/9F2ru
pFszfK9Qes8lMZ/7bqMZam45cIYURQY+6BJ8yqvj8u3we/uiGb0dwF+zOt4TkJU+
U7bqNEyB4pZsOoAQlYA/YPa4y0jTTJKFdjnKIXo/LaqKz8Mc7ONpOZHGZ25MGL+/
vxMYX2Pi0dNGsyqFBXRwuSs1Mx0sJunFf/qyIfwC3CCf6TWlAfCMNlNhoQ4idNmG
Q4hZq0BZFROjNKKuOm+Dm6qYo6VDjP/C+ttgo+N+kydq6Ieytbecys+aQBSFstuJ
ilhj9sRVmFDEze6Q4D2Q5dnuuT3ZET0U1aQ4KOcCUnPA5xrEb/iB/W3n76A/IS+4
2XHIwU8KgpQGMOegE1L9KSX9/ps1BEu1C9z10MmUZBchKydoSJBbTZKh+7+aixsK
7ruWpgU6qLxx+dqTZ7CF55m6JxAwrbbamSFfW91NA4yoNAMtkDx5KP9/fLoVnZum
B6LrSiXbD+mMJ/IqGpFSSH95EjLJO0c8U49MbQVgB5aHgt50k9sq8HtoJ7ewpEmT
sz4xGk7qg09h2SBhBWpiol7i3S96n8BdZOzpjBM0ZBu41foC9r2WFxJhs/vEnlqa
WFyoci3Fngd2+eymsme2AoQi0vHVYcLcL/0HjbU+f/5Cv0YFgj0mvoqFB+IG/ALH
KLjnVlvK3NkBqWBEmDSNS2yMqMM3KjvpwATqCUA=
KEYDATA
}

# Install another key (74C35BC8), if it isn't already, for future use.
install_future_key() {
  find_apt_trusted
  (base64 -d > "$APT_TRUSTEDDIR/vivaldi-74C35BC8.gpg") <<KEYDATA
mQINBGWvppIBEADEP5eQWayPrhnAs/AQtBAqt9KVkb5exVWsuuneyNgGBq7e8xrg
2Mh4A5+Szj1PwjGgJeAmY2g50gXHJ4rygchCZmxZ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2VryZ2PHiCT2IHPg
a3lXl40sWDtzrBDtsQeiDeeZ+GCAbmqRdwARAQABiQI8BBgBCgAmFiEEwqJEWw7D
s5a9Um4x9zmqwHTDW8gFAmWvppICGwwFCQPcxQAACgkQ9zmqwHTDW8gCVg/+MwU6
P+Ii7Kdn2BXH+BeZCrlB6/5tMsbYkaMgidpxJe07CwLO1kIwiR9EmepbcJbq2qGd
I8KNwb9hIl3mEkn5gmin9NfAo+WozeHZi3y1L4XIxlPLZqs3rn5iMPfqJSwbo59J
CUtJsYU8btL6dcWFcgUoqF/DN20VvrS837Ro0NppNLDPyFcjoTpWgEdf8t0hZtD1
/tzi6PVu9IN17i6yhzSR2IGUiun98k9DOC2QbPtg60WF9KVmycz2vgg8KJck9YgV
1nJ6qSKLii7tBlbHI9cKEqUAxEnaSyfoyKQjOmsx9MUQQ3O8oiarAlICOANo7Twq
mNecHjABcLs6eV4Ta0BLByas8RWjcWi0mBIe3BF/MzF3JyvL446UFOaHHynOjNdJ
rzUIaZtUGOvSUszNYOYm7qPGpmifDq3Tdph9wyNM8otI8IG7M8WI2HSZqcDi/urH
91433HAV2yS3G+LwXBX9mM3PpktNur+OChCX6p3Lv+9PPCxB5wl9OmuGusK+4f94
PBYDWOfoBOpBBsWNvED+3goFrU+CWtDMsXEKiaMg6TPpKWB+anqgMZR6JEYr3FuA
fo9Sa2sKm+dYTrNerUJVr5MW2FtiIVqAyTlsNqHB1z3EmfQQoYhlmtNax+p0qW6Y
GgUqMpeO5Nzvc5+8UBcSfmOp/cVgxKMaXP0rlRU=
KEYDATA
}

uninstall_key() {
  find_apt_trusted
  rm -f "$APT_TRUSTEDDIR/vivaldi-33EAAB8E.gpg" "$APT_TRUSTEDDIR/vivaldi-74C35BC8.gpg"
}

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

# Update the Google repository if it's not set correctly.
# Note: this doesn't necessarily enable the repository, it just makes sure the
# correct settings are available in the sources list.
# Returns:
# 0 - no update necessary
# 2 - error
update_bad_sources() {
  if [ ! "$REPOCONFIG" ]; then
    return 0
  fi

  find_apt_sources

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

  # Basic check for active configurations (non-blank, non-comment lines).
  ACTIVECONFIGS=$(grep -v "^[[:space:]]*\(#.*\)\?$" "$SOURCELIST" 2>/dev/null)

  # Check if the correct repository configuration is in there.
  REPOMATCH=$(grep -E "^[[:space:]#]*\b$REPOCONFIGREGEX\b" "$SOURCELIST" \
    2>/dev/null)

  # Check if the correct repository is disabled.
  MATCH_DISABLED=$(echo "$REPOMATCH" | grep "^[[:space:]]*#" 2>/dev/null)

  # Now figure out if we need to fix things.
  BADCONFIG=1
  if [ "$REPOMATCH" ]; then
    # If it's there and active, that's ideal, so nothing to do.
    if [ ! "$MATCH_DISABLED" ]; then
      BADCONFIG=0
    else
      # If it's not active, but neither is anything else, that's fine too.
      if [ ! "$ACTIVECONFIGS" ]; then
        BADCONFIG=0
      fi
    fi
  fi

  if [ $BADCONFIG -eq 0 ]; then
    return 0
  fi

  # At this point, either the correct configuration is completely missing, or
  # the wrong configuration is active. In that case, just abandon the mess and
  # recreate the file with the correct configuration. If there were no active
  # configurations before, create the new configuration disabled.
  DISABLE=""
  if [ ! "$ACTIVECONFIGS" ]; then
    DISABLE="#"
  fi
  printf "$SOURCES_PREAMBLE" > "$SOURCELIST"
  printf "$DISABLE$REPOCONFIG\n" >> "$SOURCELIST"
  if [ $? -eq 0 ]; then
    return 0
  fi
  return 2
}

# Add the Google repository to the apt sources.
# Returns:
# 0 - sources list was created
# 2 - error
create_sources_lists() {
  if [ ! "$REPOCONFIG" ]; then
    return 0
  fi

  find_apt_sources

  SOURCELIST="$APT_SOURCESDIR/vivaldi.list"
  if [ -d "$APT_SOURCESDIR" ]; then
    printf "$SOURCES_PREAMBLE" > "$SOURCELIST"
    printf "$REPOCONFIG\n" >> "$SOURCELIST"
    if [ $? -eq 0 ]; then
      return 0
    fi
  fi
  return 2
}

# Remove our custom sources list file.
# Returns:
# 0 - successfully removed, or not configured
# !0 - failed to remove
clean_sources_lists() {
  if [ ! "$REPOCONFIG" ]; then
    return 0
  fi

  find_apt_sources

  rm -f "$APT_SOURCESDIR/vivaldi.list"
}

# Detect if the repo config was disabled by distro upgrade and enable if
# necessary.
handle_distro_upgrade() {
  if [ ! "$REPOCONFIG" ]; then
    return 0
  fi

  find_apt_sources
  SOURCELIST="$APT_SOURCESDIR/vivaldi.list"
  if [ -r "$SOURCELIST" ]; then
    REPOLINE=$(grep -E "^[[:space:]]*#[[:space:]]*$REPOCONFIGREGEX[[:space:]]*# disabled on upgrade to .*" "$SOURCELIST")
    if [ $? -eq 0 ]; then
      sed -i -e "s,^[[:space:]]*#[[:space:]]*\(.*\)[[:space:]]*# disabled on upgrade to .*,\1," \
        "$SOURCELIST"
      LOGGER=$(command -v logger 2> /dev/null)
      if [ "$LOGGER" ]; then
        "$LOGGER" -t "$0" "Reverted repository modification: $REPOLINE."
      fi
    fi
  fi
}

DEFAULT_ARCH="amd64"

get_lib_dir() {
  if [ "$DEFAULT_ARCH" = "i386" ]; then
    LIBDIR=lib/i386-linux-gnu
  elif [ "$DEFAULT_ARCH" = "amd64" ]; then
    LIBDIR=lib/x86_64-linux-gnu
  elif [ "$DEFAULT_ARCH" = "armhf" ]; then
    LIBDIR=lib/arm-linux-gnueabihf
  elif [ "$DEFAULT_ARCH" = "arm64" ]; then
    LIBDIR=lib/aarch64-linux-gnu
  elif [ "$DEFAULT_ARCH" = "mipsel" ]; then
    LIBDIR=lib/mipsel-linux-gnu
  elif [ "$DEFAULT_ARCH" = "mips64el" ]; then
    LIBDIR=lib/mips64el-linux-gnuabi64
  else
    echo Unknown CPU Architecture: "$DEFAULT_ARCH"
    exit 1
  fi
}

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

install_key
install_future_key

if [ "$repo_add_once" = "true" ]; then
  create_sources_lists
  RES=$?
  # Sources creation succeeded, so stop trying.
  if [ $RES -ne 2 ]; then
    sed -i -e 's/[[:space:]]*repo_add_once=.*/repo_add_once="false"/' "$DEFAULTS_FILE"
  fi
else
  update_bad_sources
fi

if [ "$repo_reenable_on_distupgrade" = "true" ]; then
  handle_distro_upgrade
fi
