#!/bin/bash
# set -e # die on any errpr because nmama didnt raise no bitch
# even includes error handling and sanity checks plus has help and even did tha retcodes :3

# happy naesms
provided_credential="$1"
openbadge_file="$2"

# halp string
halp_str="\nHelp:\n\tAbout:\n\t\tCheckBadge for verifying Openbadges\n\t\tPart of https://github.com/PrincessPi3/general-scripts-and-system-ssssssetup Files\n\tUsage:\n\t\tcheckbadge <string credential (email or phone number)> <string path to openbadge file>\n\t\tExample:\n\t\t\tcheckbadge 'my@email.com' mybadgefile.png\n\t Requires:\n\t\t* coreutils (sha256sum)\n\t\t* jq\n\t\t* exiftool"

# sum silliness so  you can get help with retcode 0 with -h, -help, --help, --h, help, h, etc so lnog as the first arg starts with -?-?h (case insensitive) and arg two is empty
if [[ "$1" =~ ^[-]{0,2}[hH] ]]; then
    if [ -z "$2" ]; then
        echo -e "$halp_str"
        exit 0
    fi
fi

# maek sure da args are in place or print help and fail
if [ -z "$provided_credential" -o -z "$openbadge_file" ]; then
    echo -e "\nERROR: must provide the credential and the file path"
    echo -e "$halp_str"
    exit 1
fi

# does fiel exist dipshit?
if [ ! -f "$openbadge_file" ]; then
    echo -e "\nERROR: $openbadge_file not found"
    echo -e "$halp_str"
    exit 1
fi

# maek sure its an openbadges fiel
exiftool "$openbadge_file" | grep -q Openbadges
ret=$?

if [ $ret -ne 0 ]; then
    echo -e "\nERROR: File $openbadgefile does not seem to be an Openbadge file or it has had its metadata stripped"
    echo -e "$halp_str"
    exit 1
fi

# gert da json out of da metadata fo da badger
openbadge_json=$(exiftool "$openbadge_file" | grep Openbadges | awk -F ': ' '{print $2}') 

# get da values out of dat json
openbadge_url=$(echo $openbadge_json | jq -r '.badge')
openbadge_sha256=$(echo $openbadge_json | jq -r '.recipient.identity' | awk -F '$' '{print $2}')
openbadge_salt=$(echo $openbadge_json | jq -r '.recipient.salt')
openbadge_narrative=$(echo $openbadge_json | jq -r '.narrative')
openbadge_name=$(echo $openbadge_json | jq -r '.extensions.recipientProfile.name')

# generate da checksum from the provided credential and extracted salt
# sha256(<string provided credential><string extracted salt>)
generated_sha256=$(printf "$provided_credential$openbadge_salt" | sha256sum | awk '{print $1}')

# outputter
echo -e "\nTESTING '$provided_credential' AGAINST OPENBADGE FILE '$openbadge_file'\n\nProvided Credential: $provided_credential\nBadge File: $openbadge_file\n\tBadge URL: $openbadge_url\n\tSalt: $openbadge_salt\n\tNarrative: $openbadge_narrative\n\tSHA256 Checksum: $openbadge_sha256\nGenerated SHA256 Checksum: $generated_sha256\n\tFrom: sha256(<string credential><string salt>)"

# do dey maaaatch again>???
# but this time set retcode show succ or failure
if [ "$openbadge_sha256" = "$generated_sha256" ]; then
    echo -e "\nSUCCESS: VERIFIED MATCH!"
    exit 0
else
    echo -e "\nFAIL: NO MATCH!"
    exit 1
fi