#!/bin/sh
#
# Remember The Milk modifications.
#
# Copyright (c) 2015 Slack Technologies. Original version from Google Chrome,
# license is below.
#
# 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.
#
# 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/rememberthemilk"

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"

# sources.list setting for updates.
REPOCONFIG="deb https://www.rememberthemilk.com/download/linux/debian/ jessie main"

# Parse apt configuration and return requested variable value.
apt_config_val() {
  APTVAR="$1"
  if [ -x "$APT_CONFIG" ]; then
    "$APT_CONFIG" dump | sed -e "/^$APTVAR /"'!d' -e "s/^$APTVAR \"\(.*\)\".*/\1/"
  fi
}

# Install the repository signing key (see also:
# https://www.google.com/linuxrepositories/)
install_key() {
  APT_KEY="`which apt-key 2> /dev/null`"
  if [ -x "$APT_KEY" ]; then
    "$APT_KEY" add - >/dev/null 2>&1 <<KEYDATA
-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG v1

mQINBFe2ORoBEADYTuDIq/imHSfHdLJZqF8ce/7FnYI2Z+1i4SeFhzDGIqx/W5iB
kwCpMvKO/sR/vjn/Zz6hdoC0JJ0nBTLI+gWrmmOluSfKMpBX4L7+1lppt86Uox4B
S2MAC0ECjvo2/j5eGnN5sIz2cgIi6NzeIghZ+rKSef1sxmG0wh/VznKOYf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MAAoJECPAtG+53ovZzF0P/1scvbtr1LP0CQI6cToBch1rlnkfqOiamlfwA7C5
vNrw3Y3SJDnfYWfX17li/1jdWVtHOic35gJNV4UaEzuC2ENX4Wei7qtB2MJLXFLV
IaYRI+MJTo6GkMJuJxWk5UQU0qHBNGQnZ+iig7zhhptysFhCtY4gwbjvBn+LDRED
soDCF5g62BZPiEtOVq3BanyHHZbxC7XPTe/Cx+EQw/xmWOqu60BubUBrClW4Z9QR
G+U8swbUmWgcAyqAwZsePYZdmVFegaRA2oTksN/g5Sfkmf5vY40dgZzZqukf7rnb
kIlnBsQEfjQp8iX/+MbGs6RmhghnCPASrwqgf1erCVt9TVQPfl+bziKL537S+8nm
zmGvLWvG6vsePZ+CGNe2uj0N/5228C4AD7kAWNG4GdO3GmzuCVAVgJIYPxizvQfq
FqzbHIQ7T5UDd5Hq7vQir4MqdCAcN5Sh84dF75JonD+XWlJH9cU/9tgoPIaIOtEx
BuMD2Ov1nTcCSKVSKALUVmoVYuJmvDM/6B9g72DfHZ0oebrWW6KoasYzfvhr9Ni8
j7eufJ7P6EvP25DRtOI5gjVs+TeI1gatkv09Sju+vfUbnyDNsO943PT6PtGknXM4
H1ZD5XpXsG3yudSUHYFvRIDv2NDgK5VqKCApyVqSu6C9TD1pR+HyKCtGqqsdHv8F
rdQC
=5Nhv
-----END PGP PUBLIC KEY BLOCK-----
KEYDATA
  fi
}

# Set variables for the locations of the apt sources lists.
find_apt_sources() {
  APTDIR=$(apt_config_val Dir)
  APTETC=$(apt_config_val 'Dir::Etc')
  APT_SOURCES="$APTDIR$APTETC/$(apt_config_val 'Dir::Etc::sourcelist')"
  APT_SOURCESDIR="$APTDIR$APTETC/$(apt_config_val 'Dir::Etc::sourceparts')"
}

# 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/rememberthemilk.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 "^[[:space:]#]*\b$REPOCONFIG\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/rememberthemilk.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/rememberthemilk.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/rememberthemilk.list"
  if [ -r "$SOURCELIST" ]; then
    REPOLINE=$(grep -E "^[[:space:]]*#[[:space:]]*$REPOCONFIG[[:space:]]*# disabled on upgrade to .*" "$SOURCELIST")
    if [ $? -eq 0 ]; then
      sed -i -e "s,^[[:space:]]*#[[:space:]]*\($REPOCONFIG\)[[: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
  else
    echo Unknown CPU Architecture: "$DEFAULT_ARCH"
    exit 1
  fi
}

## MAIN ##
DEFAULTS_FILE="/etc/default/rememberthemilk"
if [ -r "$DEFAULTS_FILE" ]; then
  . "$DEFAULTS_FILE"
else
  repo_add_once="true"
  repo_reenable_on_distupgrade="true"
  echo "repo_add_once=\"true\"\nrepo_reenable_on_distupgrade=\"true\"\n" > "$DEFAULTS_FILE"
fi

if [ "$repo_add_once" = "true" ]; then
  install_key
  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
  install_key
fi
