#! /bin/bash
#
# This is a convenience script that generates a stub for a
# test vector.  For example:
#
#   $ ./torust simple
#       #[test]
#       #[allow(unused)]
#       fn simple() -> Result<()> {
#           let p = &StandardPolicy::new();
#
#           let alice_fpr: Fingerprint =
#               "8C38FE08E54E931B547F0734B1C8B7F2AC3CD6F3"
#              .parse().expect("valid fingerprint");
#           let alice_uid
#               = UserID::from("<alice@example.org>");
#   ...

set -e

usage() {
    echo "Usage: $0 [FILE|DIR]..." >&2
    exit 1
}

if test $# -eq 0
then
    usage
fi

dir=""
name=""
if test $# -eq 1 -a -d $1
then
    dir=$1
    name=$(echo $dir | tr -- - _)

    cat<<EOF
    #[test]
    #[allow(unused)]
    fn $name() -> Result<()> {
        let p = &StandardPolicy::new();
EOF
fi

for f in $@; do
    if test -d "$f"
    then
        # If $f is a directory, then we list all files.
        find "$f" -type f -name '*-priv.pgp' | sed 's/-priv[.]pgp$/.pgp/'
    else
        echo "$f"
    fi
done | sort | while read f
do
    sq inspect --certifications "$f" \
        | awk -F': *' '
          $1 ~ /Fingerprint/ {
            fpr = $2;
            fpr_printed = 0;
            userids = 0;
          }
          $1 ~ /UserID/ {
            userid = $2;
            userids += 1;
            email = gensub(/<(.*)>/, "\\1", "", userid);
            var = email;
            if (userids == 1) {
              sub("[@].*", "", var);
            }
            gsub("[-@.]", "_", var);

            # printf("userid: %s\n", userid);
            # printf("email: %s\n", email);
            # printf("var: %s\n", var);

            if (fpr_printed == 0) {
                printf("\n        let %s_fpr: Fingerprint =\n\            \"%s\"\n           .parse().expect(\"valid fingerprint\");\n", var, fpr);
                fpr_printed = 1;
            }
            printf("        let %s_uid\n            = UserID::from(\"%s\");\n", var, userid);
        }
        $1 ~ /Alleged certifier/ {
            printf("        // Certified by: %s\n", $2);
        }
'
done 2>/dev/null

if test x != "x$name"
then
    cat <<EOF

        let certs: Vec<Cert> = CertParser::from_bytes(
            &crate::testdata::data("$dir.pgp"))?
            .map(|c| c.expect("Valid certificate"))
            .collect();
        let n = Network::from_certs(certs.into_iter(), p, None)?;

        eprintln!("{:?}", n);

        /// Tests.

        Ok(())
    }
EOF
fi
