#!/bin/sh

set -e

ESM_APT_GPG_KEY="/etc/apt/trusted.gpg.d/ubuntu-esm-v2-keyring.gpg"
ESM_APT_GPG_KEY_OLD="/etc/apt/trusted.gpg.d/ubuntu-esm-keyring.gpg"
ESM_APT_SOURCE_FILE="/etc/apt/sources.list.d/ubuntu-esm-trusty.list"
ESM_APT_PREF_FILE="/etc/apt/preferences.d/ubuntu-esm-trusty"

configure_esm() {
    rm -f $ESM_APT_GPG_KEY_OLD  # Remove retired key from key list
    if [ ! -f "$ESM_APT_GPG_KEY" ]; then
        cp /usr/share/keyrings/ubuntu-esm-v2-keyring.gpg "$ESM_APT_GPG_KEY"
    fi

    if [ ! -e "$ESM_APT_SOURCE_FILE" ]; then
        cat > $ESM_APT_SOURCE_FILE <<EOF
# Written by ubuntu-advantage-tools
deb https://esm.ubuntu.com/ubuntu trusty-security main
# deb-src https://esm.ubuntu.com/ubuntu trusty-security main

deb https://esm.ubuntu.com/ubuntu trusty-updates main
# deb-src https://esm.ubuntu.com/ubuntu trusty-updates main
EOF
    fi
    if [ ! -e "$ESM_APT_PREF_FILE" ]; then
        ESM_POLICY=`apt-cache policy | grep https://esm.ubuntu.com | awk 'END{print $1}'`
        if [ "500" != "$ESM_POLICY" ]; then  # we are inactive
            cat > $ESM_APT_PREF_FILE <<EOF
# Written by ubuntu-advantage-tools
Package: *
Pin: release o=UbuntuESM, n=trusty
Pin-Priority: never
EOF
        fi
    fi
}

upgrade_to_status_cache() {
    # Remove all publicly-readable files
    find /var/lib/ubuntu-advantage/ -maxdepth 1 -type f -delete
    # Regenerate the status.json cache
    ua status 2>&1 > /dev/null
}

case "$1" in
    configure)
      # We changed the way we store public files in 19.5; transition to the new
      # status cache for installs of a previous version
      if dpkg --compare-versions "$2" lt-nl "19.5~"; then
          upgrade_to_status_cache
      fi

      # CACHE_DIR is no longer present or used since 19.1
      rm -rf /var/cache/ubuntu-advantage-tools

      grep -iq trusty /etc/os-release && configure_esm
      if [ ! -f /var/log/ubuntu-advantage.log ]; then
          touch /var/log/ubuntu-advantage.log
      fi
      chmod 0600 /var/log/ubuntu-advantage.log
      chown root:root /var/log/ubuntu-advantage.log
      ;;
esac

#DEBHELPER#
exit 0
