#!/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 naver-whale 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/naver-whale"

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

# 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 keys.
# (see also: https://www.google.com/linuxrepositories/)
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.
  # IF WHALE
  # Google Chrome's key data is replaced with Whale's,
  # http://repo.whale.naver.com/stable/deb/public.gpg.
  # ENDIF
  (base64 -d > "$APT_TRUSTEDDIR/naver-whale.gpg") <<KEYDATA
mQINBFntT4kBEADZtiL/NvPxPZKGmgoF6ZE75nWFS1FxAKl2dtvODEVbvX0lsOBf
qNPJMBn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W8pkAEQEAAYkCHwQYAQgA
CQUCWe1PiQIbDAAKCRDd/1k472wH9qicD/0ZzjOglyfnXpTapHorNAtG0Dr124JF
GUyazdZjNUnka24tt2o/JFa2rC0R/nIEwYdxuZjLedPXSpRlD8sLv0X49BQFtUzR
r6YBHIcpFW+Gm+aa7siiumwT9myWaM9RujXCI9AqND5PuxvScrZABiX7S5wz7oDk
KoJRsC0gO2PDWsz5d3hk56FSHLVnd/HMMoOE6/yEVhfr7IMQ/Ymd+iNXO6HypNAK
4i1HTRJw92NibrxhauKjR0GJKP0BShqddXJC/qM1sjRlna4IAanSQy9gmOGQu9zg
rdwIpfF1+5uRFeS43+87AsXVSegT/DBOwrS3xyilqWTGegqDFNZfab0s/MY6H/U7
WkZfa/DUZQmRvvokOFbZ7NtSS71V2p67AIJ4isPjFlntiL2I5resV4d2xcXrJljW
1LhmwAEwRMk48TkfC0dLY4voBS3dakRCQ2C0/ZlnM8VRFjFDSFnz6iR7/GvcUEk5
1P3p0lRsBSMU1DYqyWG9WiImqcbiQYuzXKwZOUKVcxtRHCCD6oODrhriOjkRbo8h
OJJtb1ZwfdOmH6Arj5hq6aw8rIKwmzRQ7Cxl3awXxduxwW1LCAwllWviB/7VufVh
aaU1G+Fq4aR7daE9TXyNLZwmmRanQmKVC5jC0ylWMxTl12glG3QTLni7q9YFKw3i
YaYOOaYifGTSoA==

KEYDATA
}

uninstall_key() {
  find_apt_trusted
  rm -f "$APT_TRUSTEDDIR/naver-whale.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/naver-whale.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/naver-whale.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/naver-whale.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/naver-whale.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

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
