#!/bin/sh
#
# Copyright (c) 2009 The Chromium Authors. All rights reserved.
# 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 yandex-browser-beta 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/yandex-browser-beta"

# sources.list setting for yandex-browser-beta updates.
REPOCONFIG="deb [arch=amd64] http://repo.yandex.ru/yandex-browser/deb beta main"
REPOCONFIGREGEX="deb (\[arch=[^]]*\bamd64\b[^]]*\][[:space:]]*) https?://repo.yandex.ru/yandex-browser/deb beta main"

APT_GET="`which apt-get 2> /dev/null`"
APT_CONFIG="`which 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"

# Install the repository/package signing keys, if they aren't already.
# (see also: https://www.google.com/linuxrepositories/)
install_key() {
  APT_KEY="`which apt-key 2> /dev/null`"
  if [ ! -x "$APT_KEY" ]; then
    return
  fi
  # BROWSER-81973: Always try to install Yandex PGP public key
  # without checking the same previous Chromium keys.
  NEED_KEYS=1

  # 2017 signing subkey
  "$APT_KEY" export 997C215E 2>&1 | \
    grep -q -- "-----BEGIN PGP PUBLIC KEY BLOCK-----"
  if [ $? -ne 0 ]; then
    NEED_KEYS=1
  fi

  # 2019 signing subkey
  "$APT_KEY" export 3CB3BD13 2>&1 | \
    grep -q -- "-----BEGIN PGP PUBLIC KEY BLOCK-----"
  if [ $? -ne 0 ]; then
    NEED_KEYS=1
  fi

  if [ $NEED_KEYS -eq 1 ]; then
    "$APT_KEY" add -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+U
Zq109gWKGaHOTCld1jDEaL40xbCr3hRNYWpexyH8E21AKrnV1ffEskTFODSW10zn
sG8o/rgc6gqhf3PQPhe76m+bklf4NR/uZDU3BASiVGDoi98bGgEMQZIPxE6gy72G
2Qa0KdmNoOMsAe+rvbfhVE0fqupndoCpkZCfGXNdkuL884dKiFjasJ+Eu+DCsa04
NwARAQABiQIfBBgBAgAJBQJUDa5DAhsMAAoJECGAF9HMX9s0LRkP/iGMVu0v0FkA
/mREcRVy/3zP8HD2L0+8rHoj7umq/ucAA1pxzdmv2QPWpG4GJFNHnJyNtumLgT+Y
9fuVG/glYvggIL+8G/XbjRRgt4BqVVQdWOqaagoPlwt2+gvRqoqoDc/YtgOkFroE
tJTrHwPSlGiRvVy0lHcDQ0GOPCLyu83rCj4cBRVJQEcLsq3xf41vYcQmfNatjVtI
Lc3OU7mladuVQVH+p7y1RnWsM2Abhsi5KWcxlwhfbLJuf+Ai5HGTiE2m0NZZ5DTJ
56PBVvfdX0Q5iz/CdzgEuSEMURetpgzJw5PYPj0kweVrugQwiJiYnkuGKrOa9T/r
/Pl42s8409dHA+421pIkFDIdOFZChMxZLZt/SGFDxBnbcYihTHU/uJHUPRaeNiAI
vT6Id5ed6uDM8LKi9TseCgKCH09ZObBvPPVD1h3CHcgYRk1O1wW2Izpr7/xMimYj
1RW0prWc+mZJfixBam0KuJlZtKMpYSYs7PN6yp8gXyIn2ykXhjPHtnJt7Vg+1BRm
Xgsik8Ausq7iDqNtdrQFQUmVffp20RM40XdbIaByyGBh+nnZ6iNd3o7EzecYcCbi
NGbmIRhl3pVIOud+NNMQ5e/K+6yWMUETMdbmpuSQ4/TM0uDq3COKrIex/b7Cw4m+
/cAWQBPychi5yutrZ8INB1UppITOLQv+
=OuZx
-----END PGP PUBLIC KEY BLOCK-----
KEYDATA
  fi
}

# 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/yandex-browser-beta.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/yandex-browser-beta.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/yandex-browser-beta.list" \
        "$APT_SOURCESDIR/yandex-browser-beta-beta.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/yandex-browser-beta.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=$(which 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 ##
DEFAULTS_FILE="/etc/default/yandex-browser-beta"
if [ -r "$DEFAULTS_FILE" ]; then
  . "$DEFAULTS_FILE"
fi

# Always try to install repo key
install_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
