#!/bin/bash
# Daniel Bowers July 2021
# For each package that apt reports as upgradable, report metadata on the binary from launchpad 

if ! command -v jq &> /dev/null; then
   echo "Requires jq. Try sudo apt install jq"
   exit 1
fi

if [[ -r /etc/os-release ]]; then
   . /etc/os-release
   uversion=${VERSION_CODENAME}
else
   echo "Not running Ubuntu, sorry!"
fi

apt list --upgradeable 2>/dev/null | sed 1d | while read line; do

   # Split output into separate fields
   read -ra words <<< "$line"
   IFS=/ read package pocket <<< "${words[0]}"
   pocket="$(echo $pocket | sed 's/,.*//')"
   # If updates available in more than one pocket, just look at first pocket
   version="${words[1]}"
   architecture="${words[2]}"
   if [[ "$architecture" == "all" ]]; then architecture="amd64"; fi
   # If cross-architecture, then look at amd64 packages in the repository

   # Fetch JSON-format metadata about upgradable packages from Launchpad API
   sources_json=$(curl -s "https://api.launchpad.net/1.0/ubuntu/+archive/primary?ws.op=getPublishedBinaries&exact_match=true&$pocket=Security&status=Published&distro_arch_series=https://api.launchpad.net/1.0/ubuntu/$uversion/$architecture&binary_name=$package")

   echo "Package: $package"
   echo "Pocket: $pocket"
   echo "Architecture: $architecture"
   echo "New Version Available: $version"
   echo "Dates for all versions:"

   entries=$(echo $sources_json | jq '.total_size')

   if [[ $entries -eq 0 ]]
   then
      echo "UNKNOWN"
      # Package likely not in Canonical main or universe
   else
      echo $sources_json | jq '.entries[] | "\(.binary_package_name) \(.status) \(.binary_package_version) \(.date_published)"'
      # Other useful fields in the json: display_name, date_published, status, date_removed, binary_package_name, binary_package_version, priority_name
   fi

   echo ""

done