#!/bin/bash

DATA_FILE=${1:-"package.json"}
OUT_JSON=${2:-"app.json"}
PRIVATE_KEY=${3:-"key/private_key.pem"}

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

    cat ${DATA_FILE} | gzip -f -c | base64 | tr -d ' \r\n' > ${PLAYLOAD_FILE}

    signature=$(openssl dgst -sha256 -sign ${PRIVATE_KEY} ${PLAYLOAD_FILE} |  base64 | tr -d ' \r\n')

    echo -en "{\n\t\"signature\": \"${signature}\",\n\t\"payload\": \"" > ${OUT_JSON}
    cat ${PLAYLOAD_FILE} >> ${OUT_JSON}
    echo -en "\"\n}\n" >> ${OUT_JSON}
    rm -f ${PLAYLOAD_FILE}
fi
