#!/bin/env bash
# This script downloads the latest UEFI DBXs and creates the dbx_info.h header

github_url="https://api.github.com/"

# Retrieve the commit epoch from a GitHub URL or 0 if not available
get_commit_date() {
  url=$1
  if [[ "${url}" =~ ^"${github_url}" ]]; then
    parts=($(awk -F'contents/' '{ for(i=1;i<=NF;i++) print $i }' <<< ${url}))
    date_url="${parts[0]}commits?path=${parts[1]//\//%2F}&page=1&per_page=1"
    epoch="$(curl -s -L ${date_url} | python -m json.tool | grep -m1 \"date\": | sed -e 's/^.*\"date\":.*\"\(.*\)\".*/\1/' | date -u -f - +%s)"
  fi
  echo ${epoch:-0}
}

# Should be in the same order as the ArchType enum in Rufus with the first entry (ARCH_UNKNOWN = 0) skipped
# Note that are GUESSING the RISC-V 64 and LoongArch 64 URLS since there are no DBX revocations for those archs yet.
# Also use api.github.com (which is rate limited) so we don't get the stupid 404 GitHub page on error, which is 10
# times larger than our largest DBX update binary...
declare -a dbx_urls=(
  'https://api.github.com/repos/microsoft/secureboot_objects/contents/PostSignedObjects/DBX/x86/DBXUpdate.bin'
  'https://api.github.com/repos/microsoft/secureboot_objects/contents/PostSignedObjects/DBX/amd64/DBXUpdate.bin'
  'https://api.github.com/repos/microsoft/secureboot_objects/contents/PostSignedObjects/DBX/arm/DBXUpdate.bin'
  'https://api.github.com/repos/microsoft/secureboot_objects/contents/PostSignedObjects/DBX/arm64/DBXUpdate.bin'
  'https://api.github.com/repos/microsoft/secureboot_objects/contents/PostSignedObjects/DBX/ia64/DBXUpdate.bin'
  'https://api.github.com/repos/microsoft/secureboot_objects/contents/PostSignedObjects/DBX/riscv64/DBXUpdate.bin'
  'https://api.github.com/repos/microsoft/secureboot_objects/contents/PostSignedObjects/DBX/loongarch64/DBXUpdate.bin'
)

cat << EOF > dbx_info.h
// Autogenerated - DO NOT EDIT

#include <stdint.h>
#pragma once

struct {
	char* url;
	uint64_t timestamp;
} dbx_info[] = {
EOF
for url in "${dbx_urls[@]}"; do
  if [[ ! -z "${url}" ]]; then
    dst=$(echo ${url} | cut -f10,11 -d'/' | tr '/' '_')
    curl -L -H "Accept: application/vnd.github.v3.raw" "${url}" -o "${dst}"
    fgrep -q "Not Found" "${dst}" && :> "${dst}"
  fi
  echo "	{ \"${url}\", $(get_commit_date ${url}) }," >> dbx_info.h
done
echo "};" >> dbx_info.h
