#!/bin/bash

INPUT_FILE=${1:-"app.json"}
OUTPUT_FILE=${2:-"decrypted_data.json"}
PRIVATE_KEY=${3:-"key/private_key.pem"}

if [[ -f "${PRIVATE_KEY}" && -f "${INPUT_FILE}" ]]; then
    PLAYLOAD_FILE=$(mktemp ./payload_b64.XXXXXX)

    # Extract the signature and payload from the input file
    SIGNATURE=$(jq -r '.signature' ${INPUT_FILE})
    PAYLOAD=$(jq -r '.payload' ${INPUT_FILE})

    # Create a temporary file to store the decoded payload
    PAYLOAD_FILE=$(mktemp ./payload.XXXXXX)

    # Decode the base64-encoded payload and write it to the temporary file
    echo "${PAYLOAD}" | base64 -d > ${PAYLOAD_FILE}

    # Verify the signature using OpenSSL
    openssl dgst -sha256 -verify ${PRIVATE_KEY} -signature ${SIGNATURE} ${PAYLOAD_FILE} && echo "Signature verified" || echo "Invalid signature"

    # Decompress the payload using gzip
    zcat ${PAYLOAD_FILE} > ${OUTPUT_FILE}

    # Remove the temporary files
    # rm -f ${PLAYLOAD_FILE} ${PAYLOAD_FILE}
else
    echo "Usage: ${0} <input-file> <output-file> <private-key>"
fi
