#!/bin/bash
#
# Download and verify that the FDroid.apk is signed by the right PGP
# key.  The gpg key model is to trust only the key that is included in
# this script, so there is a test to check that it is starting with an
# empty keyring.
#
# To be run in a daily cronjob at a random time of day, e.g.:
#
#   0 0 * * *   perl -le 'sleep rand 86400'; ./check-fdroid-apk
#
# One instance of this is here:
# https://verification.f-droid.org/check-fdroid-apk/

set -e

curl="curl --user-agent F-Droid"
gpg="gpg"
if [ "$1" = "-v" ]; then
    set -x
    verbose=true
else
    curl="$curl --silent"
    gpg="$gpg --quiet"
    verbose=false
fi

test -e /tmp/.testfiles || mkdir /tmp/.testfiles
dldir=`mktemp -d /tmp/.testfiles/run-tests.XXXX`

export GNUPGHOME="$dldir"

key="${dldir}/key.asc"
apk="${dldir}/FDroid.apk"
asc="${apk}.asc"
log=/var/www/html/check-fdroid-apk/`date +%s`.txt

$curl --user-agent F-Droid https://f-droid.org/FDroid.apk > $apk
$curl --user-agent F-Droid https://f-droid.org/FDroid.apk.asc > $asc

fingerprint=37D2C98789D8311948394E3E41E7044E1DBA2E89

cat > $key <<- EOF
-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG v1
Comment: GPG for Android - https://guardianproject.info/code/gnupg/

[encoded data, 16640 characters]
893KN8JX2ozmsF4k
=w75J
-----END PGP PUBLIC KEY BLOCK-----
EOF

! $gpg --list-keys | grep pub
$gpg --import $key
$gpg --list-key --fingerprint | tr -d '[:space:]' | grep $fingerprint > /dev/null
echo ${fingerprint}:6: | $gpg --import-ownertrust > /dev/null 2>&1
sha256=`sha256sum $apk`
echo $sha256 >> $log
touch ${log}.${sha256}
if $gpg --batch --trust-model always --verify $asc $apk >> $log 2>&1; then
    rm -rf $dldir
else
    echo Failed to verify $apk
    touch ${log}.failed
fi
