#!/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 rememberthemilk package, modified from the google-chrome package.
#
# It creates the repository configuration file for package updates, since
# we cannot do this during the google-chrome installation since the repository
# is locked.
#
# This functionality can be controlled by creating the $DEFAULTS_FILE and
# setting "repo_add_once" to "true" or "false" as desired. An empty
# $DEFAULTS_FILE is the same as setting the value to "false".

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

# sources.list setting for rememberthemilk updates.
REPOCONFIG="https://www.rememberthemilk.com/download/linux/fedora/21"

# Install the repository signing key (see also:
# https://www.google.com/linuxrepositories/)
install_rpm_key() {
  # Check to see if key already exists.
  rpm -q gpg-pubkey-b9de8bd9-57b6391a > /dev/null 2>&1
  if [ "$?" -eq "0" ]; then
    # Key already exists
    return 0
  fi
  # This is to work around a bug in RPM 4.7.0. (see http://crbug.com/22312)
  rpm -q gpg-pubkey-b9de8bd9-57b6391a > /dev/null 2>&1
  if [ "$?" -eq "0" ]; then
    # Key already exists
    return 0
  fi

  # RPM on Mandriva 2009 is dumb and does not understand "rpm --import -"
  TMPKEY=$(mktemp /tmp/rememberthemilk.sig.XXXXXX)
  if [ -n "$TMPKEY" ]; then
    cat > "$TMPKEY" <<KEYDATA
-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG v1

mQINBFe2ORoBEADYTuDIq/imHSfHdLJZqF8ce/7FnYI2Z+1i4SeFhzDGIqx/W5iB
kwCpMvKO/sR/vjn/Zz6hdoC0JJ0nBTLI+gWrmmOluSfKMpBX4L7+1lppt86Uox4B
S2MAC0ECjvo2/j5eGnN5sIz2cgIi6NzeIghZ+rKSef1sxmG0wh/VznKOYfR+5BvR
VUEzLL+oSPUjAjgfB3mWEVouN0j7tysefq0pVyXLa5r8qMReJYq8grLV68hDYnEa
lozGKF5yTZkgB15EB2/SFXSphqOQKcgwPouW1hzTXsSH/TtJpCE23I50nUXFR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RI+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
    rpm --import "$TMPKEY"
    rc=$?
    rm -f "$TMPKEY"
    if [ "$rc" -eq "0" ]; then
      return 0
    fi
  fi
  return 1
}

determine_rpm_package_manager() {
  local RELEASE
  LSB_RELEASE="$(which lsb_release 2> /dev/null)"
  if [ -x "$LSB_RELEASE" ]; then
    RELEASE=$(lsb_release -i 2> /dev/null | sed 's/:\t/:/' | cut -d ':' -f 2-)
    case $RELEASE in
    "Fedora")
      PACKAGEMANAGER=yum
      ;;
    "Mageia"|"MandrivaLinux")
      PACKAGEMANAGER=urpmi
      ;;
    "SUSE LINUX")
      PACKAGEMANAGER=yast
      ;;
    esac
  fi

  if [ "$PACKAGEMANAGER" ]; then
    return
  fi

  # Fallback methods that are probably unnecessary on modern systems.
  if [ -f "/etc/lsb-release" ]; then
    # file missing on Fedora, does not contain DISTRIB_ID on OpenSUSE.
    eval $(sed -e '/DISTRIB_ID/!d' /etc/lsb-release)
    case $DISTRIB_ID in
    MandrivaLinux)
      PACKAGEMANAGER=urpmi
      ;;
    esac
  fi

  if [ "$PACKAGEMANAGER" ]; then
    return
  fi

  if [ -f "/etc/fedora-release" ] || [ -f "/etc/redhat-release" ]; then
    PACKAGEMANAGER=yum
  elif [ -f "/etc/SuSE-release" ]; then
    PACKAGEMANAGER=yast
  elif [ -f "/etc/mandriva-release" ]; then
    PACKAGEMANAGER=urpmi
  fi
}

DEFAULT_ARCH="x86_64"
YUM_REPO_FILE="/etc/yum.repos.d/rememberthemilk.repo"
ZYPPER_REPO_FILE="/etc/zypp/repos.d/rememberthemilk.repo"
URPMI_REPO_FILE="/etc/urpmi/urpmi.cfg"

install_yum() {
  install_rpm_key

  if [ ! "$REPOCONFIG" ]; then
    return 0
  fi

  if [ -d "/etc/yum.repos.d" ]; then
cat > "$YUM_REPO_FILE" << REPOCONTENT
[rememberthemilk]
name=rememberthemilk
baseurl=$REPOCONFIG/\$basearch
enabled=1
gpgcheck=1
gpgkey=https://www.rememberthemilk.com/download/rememberthemilk-pkg.asc
sslverify=1
sslcacert=/etc/pki/tls/certs/ca-bundle.crt
REPOCONTENT
  fi
}

# This is called by the cron job, rather than in the RPM postinstall.
# We cannot do this during the install when urpmi is running due to
# database locking. We also need to enable the repository, and we can
# only do that while we are online.
# see: https://qa.mandriva.com/show_bug.cgi?id=31893
configure_urpmi() {
  if [ ! "$REPOCONFIG" ]; then
    return 0
  fi

  urpmq --list-media | grep -q -s "^rememberthemilk$"
  if [ "$?" -eq "0" ]; then
    # Repository already configured
    return 0
  fi
  urpmi.addmedia --update \
    "rememberthemilk" "$REPOCONFIG/$DEFAULT_ARCH"
}

install_urpmi() {
  # urpmi not smart enough to pull media_info/pubkey from the repository?
  install_rpm_key

  # Defer urpmi.addmedia to configure_urpmi() in the cron job.
  # See comment there.
  #
  # urpmi.addmedia --update \
  #   "rememberthemilk" "$REPOCONFIG/$DEFAULT_ARCH"
}

install_yast() {
  if [ ! "$REPOCONFIG" ]; then
    return 0
  fi

  # We defer adding the key to later. See comment in the cron job.

  # Ideally, we would run: zypper addrepo -t YUM -f \
  # "$REPOCONFIG/$DEFAULT_ARCH" "rememberthemilk"
  # but that does not work when zypper is running.
  if [ -d "/etc/zypp/repos.d" ]; then
cat > "$ZYPPER_REPO_FILE" << REPOCONTENT
[rememberthemilk]
name=rememberthemilk
enabled=1
autorefresh=1
baseurl=$REPOCONFIG/$DEFAULT_ARCH
type=rpm-md
keeppackages=0
REPOCONTENT
  fi
}

# Check if the automatic repository configuration is done, so we know when to
# stop trying.
verify_install() {
  # It's probably enough to see that the repo configs have been created. If they
  # aren't configured properly, update_bad_repo should catch that when it's run.
  case $1 in
  "yum")
    [ -f "$YUM_REPO_FILE" ]
    ;;
  "yast")
    [ -f "$ZYPPER_REPO_FILE" ]
    ;;
  "urpmi")
    urpmq --list-url | grep -q -s "\brememberthemilk\b"
    ;;
  esac
}

# Update the Google repository if it's not set correctly.
update_bad_repo() {
  if [ ! "$REPOCONFIG" ]; then
    return 0
  fi

  determine_rpm_package_manager

  case $PACKAGEMANAGER in
  "yum")
    update_repo_file "$YUM_REPO_FILE"
    ;;
  "yast")
    update_repo_file "$ZYPPER_REPO_FILE"
    ;;
  "urpmi")
    update_urpmi_cfg
    ;;
  esac
}

update_repo_file() {
  REPO_FILE="$1"

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

  # Check if the correct repository configuration is in there.
  REPOMATCH=$(grep "^baseurl=$REPOCONFIG/$DEFAULT_ARCH" "$REPO_FILE" \
    2>/dev/null)
  # If it's there, nothing to do
  if [ "$REPOMATCH" ]; then
    return 0
  fi

  # Check if it's there but disabled by commenting out (as opposed to using the
  # 'enabled' setting).
  MATCH_DISABLED=$(grep "^[[:space:]]*#.*baseurl=$REPOCONFIG/$DEFAULT_ARCH" \
    "$REPO_FILE" 2>/dev/null)
  if [ "$MATCH_DISABLED" ]; then
    # It's OK for it to be disabled, as long as nothing bogus is enabled in its
    # place.
    ACTIVECONFIGS=$(grep "^baseurl=.*" "$REPO_FILE" 2>/dev/null)
    if [ ! "$ACTIVECONFIGS" ]; then
      return 0
    fi
  fi

  # If we get here, the correct repository wasn't found, or something else is
  # active, so fix it. This assumes there is a 'baseurl' setting, but if not,
  # then that's just another way of disabling, so we won't try to add it.
  sed -i -e "s,^baseurl=.*,baseurl=$REPOCONFIG/$DEFAULT_ARCH," "$REPO_FILE"
}

update_urpmi_cfg() {
  REPOCFG=$(urpmq --list-url | grep "\brememberthemilk\b")
  if [ ! "$REPOCFG" ]; then
    # Don't do anything if the repo isn't there, since that probably means the
    # user deleted it.
    return 0
  fi

  # See if it's the right repo URL
  REPOMATCH=$(echo "$REPOCFG" | grep "\b$REPOCONFIG/$DEFAULT_ARCH\b")
  # If so, nothing to do
  if [ "$REPOMATCH" ]; then
    return 0
  fi

  # Looks like it's the wrong URL, so recreate it.
  urpmi.removemedia "rememberthemilk" && \
    urpmi.addmedia --update "rememberthemilk" "$REPOCONFIG/$DEFAULT_ARCH"
}

# We only remove the repository configuration during a purge. Since RPM has
# no equivalent to dpkg --purge, the code below is actually never used. We
# keep it only for reference purposes, should we ever need it.
#
#remove_yum() {
#  rm -f "$YUM_REPO_FILE"
#}
#
#remove_urpmi() {
#  # Ideally, we would run: urpmi.removemedia "rememberthemilk"
#  # but that does not work when urpmi is running.
#  # Sentinel comment text does not work either because urpmi.update removes
#  # all comments. So we just delete the entry that matches what we originally
#  # inserted. If such an entry was added manually, that's tough luck.
#  if [ -f "$URPMI_REPO_FILE" ]; then
#    sed -i '\_^rememberthemilk $REPOCONFIG/$DEFAULT_ARCH {$_,/^}$/d' "$URPMI_REPO_FILE"
#  fi
#}
#
#remove_yast() {
#  # Ideally, we would run: zypper removerepo "rememberthemilk"
#  # but that does not work when zypper is running.
#  rm -f /etc/zypp/repos.d/rememberthemilk.repo
#}

DEFAULT_ARCH="x86_64"

get_lib_dir() {
  if [ "$DEFAULT_ARCH" = "i386" ]; then
    LIBDIR=lib
  elif [ "$DEFAULT_ARCH" = "x86_64" ]; then
    LIBDIR=lib64
  else
    echo Unknown CPU Architecture: "$DEFAULT_ARCH"
    exit 1
  fi
}

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

if [ "$repo_add_once" = "true" ]; then
  determine_rpm_package_manager

  # The initial install happens in the post-install scripts, but there have been
  # reports of configuration problems, so just verify that everything looks
  # good, and if not, try to install again.
  verify_install $PACKAGEMANAGER
  if [ $? -ne 0 ]; then
    install_${PACKAGEMANAGER}
  fi

  # Now do any extra configuration that couldn't be done by post-install.
  case $PACKAGEMANAGER in
  "urpmi")
    # We need to configure urpmi after the install has finished.
    # See configure_urpmi() for details.
    configure_urpmi
    ;;
  "yast")
    # It looks as though yast/zypper has a lock on the RPM DB during
    # postinstall, so we cannot add the signing key with install_rpm_key().
    # Instead, we attempt to do this here. If the user attempt to update before
    # the cron job imports the key, Yast will grab the key from our server and
    # prompt the user to accept the key.
    install_rpm_key
    ;;
  esac

  if [ $? -eq 0 ]; then
    # Before we quit auto-configuration, check that everything looks sane, since
    # part of this happened during package install and we don't have the return
    # value of that process.
    verify_install $PACKAGEMANAGER
    if [ $? -eq 0 ]; then
      sed -i -e 's/[[:space:]]*repo_add_once=.*/repo_add_once="false"/' \
        "$DEFAULTS_FILE"
    fi
  fi
else
  update_bad_repo
fi
