#!/bin/bash
# Copyright 2020 Canonical, Ltd.
# Author: Alex Murray <alex.murray@canonical.com>
#
# Checks each certificate shipped in the ca-certificates package for each
# known Ubuntu release to see if it has expired
set -euo pipefail

# shellcheck source=/dev/null
source ~/.ubuntu-security-tools.conf
release_list=${release_list:-trusty xenial bionic focal impish jammy}
dir=$(mktemp -d)
cd "$dir" || exit
git clone --quiet https://git.launchpad.net/ubuntu/+source/ca-certificates
# certdata2pem.py fails for precise
for release in $release_list; do
  cd ca-certificates
  (git checkout --quiet "ubuntu/$release-security" || git checkout --quiet "ubuntu/$release-updates" || git checkout --quiet "ubuntu/$release" || true) 1>/dev/null 2>&1
  series=$(git branch --show-current)
  cd mozilla
  python3 certdata2pem.py 1>/dev/null 2>&1 || echo "certdata2pem.py failed for $series"
  certs=$(find . -name "*.crt")
  if [ -n "$certs" ]; then
    now_epoch=$(date +%s);
    # look for certificates expiring in the next 90 days
    expire=$((now_epoch-$((90*24*60*60))))
    for crt in $certs; do
      end=$(openssl x509 -noout -dates < "$crt" | grep notAfter= | cut -f2 -d=)
      end_epoch=$(date +%s -d "$end");
      if [ "$expire" -gt "$end_epoch" ]; then
        echo "$crt in ca-certificates in $series has expired or will expire soon on $end";
      fi;
    done
    rm -f ./*.crt
  fi
  cd ../..
done
rm -rf "$dir"
