#!/bin/sh

set -e

. /etc/os-release  # For VERSION_ID


APT_TRUSTED_KEY_DIR="/etc/apt/trusted.gpg.d"
UA_KEYRING_DIR="/usr/share/keyrings/"

ESM_INFRA_KEY_TRUSTY="ubuntu-advantage-esm-infra-trusty.gpg"

APT_SRC_DIR="/etc/apt/sources.list.d"
APT_PREFERENCES_DIR="/etc/apt/preferences.d"
ESM_APT_SOURCE_FILE_PRECISE="$APT_SRC_DIR/ubuntu-esm-precise.list"
ESM_APT_SOURCE_FILE_TRUSTY="$APT_SRC_DIR/ubuntu-esm-trusty.list"
ESM_INFRA_OLD_APT_SOURCE_FILE_TRUSTY="$APT_SRC_DIR/ubuntu-esm-infra-trusty.list"
ESM_INFRA_APT_SOURCE_FILE_TRUSTY="$APT_SRC_DIR/ubuntu-esm-infra.list"

ESM_APT_PREF_FILE_TRUSTY="/etc/apt/preferences.d/ubuntu-esm-trusty"
ESM_INFRA_OLD_APT_PREF_FILE_TRUSTY="/etc/apt/preferences.d/ubuntu-esm-infra-trusty"
ESM_INFRA_APT_PREF_FILE_TRUSTY="/etc/apt/preferences.d/ubuntu-esm-infra"

MYARCH="$(dpkg --print-architecture)"
ESM_SUPPORTED_ARCHS="i386 amd64"

SYSTEMD_WANTS_AUTO_ATTACH_LINK="/etc/systemd/system/multi-user.target.wants/ua-auto-attach.service"
SYSTEMD_HELPER_ENABLED_AUTO_ATTACH_DSH="/var/lib/systemd/deb-systemd-helper-enabled/ua-auto-attach.service.dsh-also"
SYSTEMD_HELPER_ENABLED_WANTS_LINK="/var/lib/systemd/deb-systemd-helper-enabled/multi-user.target.wants/ua-auto-attach.service"

REBOOT_CMD_MARKER_FILE="/var/lib/ubuntu-advantage/marker-reboot-cmds-required"

# Rename apt config files for ua services removing ubuntu release names
redact_ubuntu_release_from_ua_apt_filenames() {
    DIR=$1
    UA_SERVICES=$(python3 -c "
from uaclient.entitlements import ENTITLEMENT_CLASS_BY_NAME
print(*ENTITLEMENT_CLASS_BY_NAME.keys(), sep=' ')
")

    for file in "$DIR"/*; do
        release_name=""
        case "$file" in
            *-trusty*)
                release_name=trusty;;
            *-xenial*)
                release_name=xenial;;
            *-bionic*)
                release_name=bionic;;
            *-focal*)
                release_name=focal;;
            *-groovy*)
                release_name=groovy;;
            *) release_name="";;
         esac
         if [ "$release_name" ]; then
             # We have a ubuntu release name in the apt config.
             # Remove $release_name from original $file.
             new_file=${file%-${release_name}*}${file#*${release_name}}
             for service in ${UA_SERVICES}; do
                 if [ "${file#*$service}" != "$file" ]; then
                      # Valid apt cfg file for an ubuntu-advantage service
                      mv "$file" "$new_file"
                 fi
             done
         fi
    done
}


# Check cached service status from status.json and return 0 if enabled else 1
check_service_is_enabled() {
    service_name=$1
    _RET=$(python3 -c "
import os
import json
from uaclient.config import UAConfig
cfg = UAConfig()
status = cfg.read_cache('status-cache')
if status:
    for service in status['services']:
       if service['name'] == '${service_name}':
           print(service['status'])
")
   if [ "${_RET}" = "enabled" ]; then
       return  0
   else
       return  1
   fi
}


unconfigure_esm() {
    if ! check_service_is_enabled esm-infra; then
        rm -f $APT_TRUSTED_KEY_DIR/ubuntu-esm*gpg  # Remove previous esm keys
        rm -f $APT_TRUSTED_KEY_DIR/$ESM_INFRA_KEY_TRUSTY
        rm -f $ESM_INFRA_APT_SOURCE_FILE_TRUSTY
        rm -f $ESM_INFRA_OLD_APT_SOURCE_FILE_TRUSTY
        rm -f $ESM_APT_PREF_FILE_TRUSTY $ESM_INFRA_OLD_APT_PREF_FILE_TRUSTY
        rm -f $ESM_INFRA_APT_PREF_FILE_TRUSTY
    fi
}


configure_esm() {
    rm -f $APT_TRUSTED_KEY_DIR/ubuntu-esm*gpg  # Remove previous esm keys
    if [ ! -f "$APT_TRUSTED_KEY_DIR/$ESM_INFRA_KEY_TRUSTY" ]; then
        cp $UA_KEYRING_DIR/$ESM_INFRA_KEY_TRUSTY $APT_TRUSTED_KEY_DIR
    fi

    if [ -e "$ESM_APT_SOURCE_FILE_TRUSTY" ]; then
        mv $ESM_APT_SOURCE_FILE_TRUSTY $ESM_INFRA_APT_SOURCE_FILE_TRUSTY
    fi
    if [ -e "$ESM_APT_PREF_FILE_TRUSTY" ]; then
        mv $ESM_APT_PREF_FILE_TRUSTY $ESM_INFRA_APT_PREF_FILE_TRUSTY
    fi
    if [ ! -e "$ESM_INFRA_APT_SOURCE_FILE_TRUSTY" ]; then
        cat > $ESM_INFRA_APT_SOURCE_FILE_TRUSTY <<EOF
# Written by ubuntu-advantage-tools
deb https://esm.ubuntu.com/ubuntu trusty-infra-security main
# deb-src https://esm.ubuntu.com/ubuntu trusty-infra-security main

deb https://esm.ubuntu.com/ubuntu trusty-infra-updates main
# deb-src https://esm.ubuntu.com/ubuntu trusty-infra-updates main
EOF
        # Automatically disable esm sources via apt preferences until enabled
        cat > $ESM_INFRA_APT_PREF_FILE_TRUSTY <<EOF
# Written by ubuntu-advantage-tools
Package: *
Pin: release o=UbuntuESM, n=trusty
Pin-Priority: never
EOF
    fi
}


# If held fips packages exist, we are on a FIPS PRO machine with FIPS enabled
mark_reboot_for_fips_pro() {
    FIPS_HOLDS=$(apt-mark showholds | grep -E 'fips|libssl1|openssh-client|openssh-server|linux-fips|openssl|strongswan' || exit 0)
    if [ "$FIPS_HOLDS" ]; then
       mark_reboot_cmds_as_needed MESSAGE_FIPS_REBOOT_REQUIRED
    fi
}


mark_reboot_cmds_as_needed() {
    msg_name=$1
    if [ ! -f "$REBOOT_CMD_MARKER_FILE" ]; then
      touch $REBOOT_CMD_MARKER_FILE
    fi
    python3 -c "
from uaclient.config import UAConfig
from uaclient.status import ${msg_name}
cfg = UAConfig()
cfg.add_notice(label='', description=${msg_name})
"
}

case "$1" in
    configure)
      PREVIOUS_PKG_VER=$2
      # Special case: legacy precise creds allowed for trusty esm
      # do-release-upgrade substitutes s/precise/trusty/ in all apt sources.
      # So all we need to do is rename the precise sources file to trusty.
      # https://github.com/CanonicalLtd/ubuntu-advantage-client/issues/693
      if [ -e "$ESM_APT_SOURCE_FILE_PRECISE" ]; then
          mv $ESM_APT_SOURCE_FILE_PRECISE \
              $ESM_INFRA_APT_SOURCE_FILE_TRUSTY
      fi

      # We changed the way we store public files in 19.5
      if dpkg --compare-versions "$PREVIOUS_PKG_VER" lt-nl "19.5~"; then
          # Remove all publicly-readable files
          find /var/lib/ubuntu-advantage/ -maxdepth 1 -type f -delete
      fi

      # Are we upgrading from a previously release Ubuntu Advantage Pro pkg?
      # We broke package compatibility in 20.2 for any image with 19.7
      if dpkg --compare-versions "$PREVIOUS_PKG_VER" lt-nl "20.2~"; then
          if dpkg --compare-versions "$PREVIOUS_PKG_VER" ge-nl "19.7~"; then
              # Drop stale symlinks for migrated auto-attach-service
              rm -f $SYSTEMD_WANTS_AUTO_ATTACH_LINK
              rm -f $SYSTEMD_HELPER_ENABLED_AUTO_ATTACH_DSH
              rm -f $SYSTEMD_HELPER_ENABLED_WANTS_LINK
              # Use debconf to alert the user to the additional
              # ubuntu-advantage-pro package that should be installed
              . /usr/share/debconf/confmodule
              db_input high ubuntu-advantage-tools/suggest_pro_pkg || true
              db_go || true
          fi
      fi

      # UA service PPAs support all ubuntu releases, no need to
      # specialize apt config filenames per ubuntu release.
      redact_ubuntu_release_from_ua_apt_filenames $APT_SRC_DIR
      redact_ubuntu_release_from_ua_apt_filenames $APT_PREFERENCES_DIR

      # CACHE_DIR is no longer present or used since 19.1
      rm -rf /var/cache/ubuntu-advantage-tools
      # machine-access cache files no longer present or used since 20.1
      rm -f /var/lib/ubuntu-advantage/private/machine-access-*.json

      if [ "14.04" = "$VERSION_ID" ]; then
        if echo "$ESM_SUPPORTED_ARCHS" | grep -qw "$MYARCH"; then
          # 14.04 and supported arch
          configure_esm
        else
          # 14.04 and unsupported arch
          unconfigure_esm
        fi
      fi

      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
      private_dir="/var/lib/ubuntu-advantage/private"
      if [ -d "$private_dir" ]; then
          chmod 0700 "$private_dir"
      fi

      if [ "$VERSION_ID" = "16.04" ]; then
        if echo "$PREVIOUS_PKG_VER" | grep -q "14.04"; then
          mark_reboot_cmds_as_needed MESSAGE_LIVEPATCH_LTS_REBOOT_REQUIRED
        fi
      fi
      mark_reboot_for_fips_pro
      ;;
esac

#DEBHELPER#
exit 0
