#!/bin/bash

function read_key()
{
  bsdtar -xOf "$1" -- "${2}/desc" | grep "%${3}%" -A 1 | tail -n1
}

verbosity_=0
while getopts "hv" flag; do
  case "$flag" in
    v)
      verbosity_=$((verbosity_ + 1))
    ;;
    h)
      echo """usage: ${0##*/} [-h] [-v] [database, database, ...]
  Check signature entries in the given pacman databases against the signature
  files in the same directory.

    -v  Increase verbosity. Pass multiple times for more.
"""
      exit 0
    ;;
  esac
done
shift $((OPTIND - 1))

dbok=true
for db in "$@"
do
  db="$(readlink -f -- "$db")"
  if [[ $verbosity_ -gt 0 ]]
  then
    echo "checking database $db"
  fi
  pushd -- "${db%/*}" > /dev/null
  bsdtar --exclude '*/?*'  -tf "$db" | \
  while read -- pkg
  do
    pkg="${pkg%/}"
    if [[ $verbosity_ -gt 1 ]]
    then
      echo "checking entry for $pkg"
    fi
    arch="$(read_key "$db" "$pkg" ARCH)"
    sig="${pkg}-${arch}.pkg.tar.xz.sig"
    if [[ ! -e $sig ]]
    then
      echo """missing file
  $db
  $sig"""
      dbok=false
      continue
    fi
    real_sig="$(base64 -w 0 -- "$sig")"
    db_sig="$(read_key "$db" "$pkg" PGPSIG)"
    if [[ -z $db_sig ]]
    then
      echo """missing entry
  $db
  $sig"""
      dbok=false
      continue
    elif [[ $real_sig != $db_sig ]]
    then
      echo """mismatch
  $db
  $sig"""
      dbok=false
    fi
  done
  popd > /dev/null
done

if ! $dbok
then
  exit 1
fi
