#!/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))

db_ok=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)"
    db_sig="$(read_key "$db" "$pkg" PGPSIG)"
    for sig in "${pkg}-${arch}.pkg."*.sig
    do
      real_sig="$(base64 -w 0 -- "$sig")"
      if [[ -z $db_sig ]]
      then
        echo """missing entry
  $db
  $sig"""
        db_ok=false
        continue
      elif [[ $real_sig != $db_sig ]]
      then
        echo """mismatch
  $db
  $sig"""
        db_ok=false
      fi
    done
  done
  popd > /dev/null
done

if ! $db_ok
then
  exit 1
fi
