#!/bin/bash

RD=$(realpath ${REACTOR_DATA_PREFIX:-.})
RH=$(realpath ${REACTOR_HOME:-.})


if [ "$1" != "-d" ]; then
    echo "Running version 22003; installed in ${RH}; data in ${RD}"

    [ -f app.js ] || { echo "Please cd to the Reactor installation directory, and run: bash tools/$( basename $0 )"; exit 255; }

    echo "This script will gather and package configuration and runtime data."
    echo "THIS WILL INCLUDE YOUR PRIVATE INFORMATION. THE OUTPUT IS ENCRYPTED"
    echo "AND CAN ONLY BE DECRYPTED BY AUTHORIZED INDIVIDUALS HAVING THE NECESSARY"
    echo "DECRYPTION KEYS. NONETHELESS, IF YOU POST, UPLOAD OR EMAIL THIS DATA,"
    echo "BE AWARE THAT YOU ARE TRANSMITTING YOUR PRIVATE DATA."
    echo -e -n "If you understand and agree, type AGREE: "
    read ans
    if [ "x$ans" != "xAGREE" ]; then
        echo "Aborted! No package created in this run."
        exit 255;
    fi
fi

T=${TMP:-/tmp}
F="msr-state$$"
D="$T/$F"
B=$(date +%F.%T%z)

mkdir -p ${D}
echo $ans ${USER} $(hostname) $(hostname -i) > ${D}/.timestamp-${B}
curl -s -o ${D}/engine-${B}.json 'http://127.0.0.1:8111/api/v1/engine/status'
curl -s -o ${D}/structure-${B}.json 'http://127.0.0.1:8111/api/v1/structure'
curl -s -o ${D}/capabilities-${B}.json 'http://127.0.0.1:8111/api/v1/capabilities'
curl -s -o ${D}/sun-${B}.json 'http://127.0.0.1:8111/diag/sun'
fgrep -r 'const version' ${RH} | fgrep -v '/node_modules/' > ${D}/versions.lst
if [ "$RD" != "$RH" ]; then
    fgrep -r 'const version' ${RD} | fgrep -v '/node_modules/' >> ${D}/versions.lst
fi
( echo -n "node "; node -v ) >> ${D}/versions.lst
npm ls >> ${D}/versions.lst
npm ls -g >> ${D}/versions.lst

mkdir -p ${D}/config ${D}/server ${D}/storage ${D}/logs || exit $?
cp -r ${RD}/config/* ${D}/config/ || exit $?
cp -r ${RD}/storage/* ${D}/storage/ || exit $?
cp -r ${RD}/logs/* ${D}/logs/ || exit $?
cp -r ${RH}/server/lib/*.{json,yaml} ${D}/server/ || exit $?

tar -C ${T} -c -z -f ${D}.taz ${F}
# Generate random key for encryption of data
openssl rand -base64 2048 > ${T}/rand.$$
# Encrypt data using random key
openssl aes-256-cbc -md sha512 -pbkdf2 -salt -in ${D}.taz -out ${D}.bin -pass file:${T}/rand.$$
rm -rf ${D} ${D}.taz
# Encrypt encryption key using our certificate (public key). This cannot be decrypted without
# the private key (which only toggledbits holds).
openssl smime -encrypt -binary -in ${T}/rand.$$ -out ${D}.pin -aes256 server/reactor.crt
# Now remove the plaintext encryption key
rm -f ${T}/rand.$$
# Create a new archive with the encrypted key and data. This keeps all in one file.
FINAL=${RD}/${F}.tar
tar -C ${T} -c -f ${FINAL} ${F}.bin ${F}.pin && rm -f ${T}/${F}.bin ${T}/${F}.pin

if [ "$1" == "-d" ]; then
    echo ${FINAL}
else
    echo ""
    echo "The status archive has been created: ${FINAL}"
    echo "DO NOT TRANSMIT ANY OTHER FILE, ONLY THE FILE NAMED ABOVE!"
    echo "THIS FILE CONTAINS ENCRYPTED DATA FOR YOUR PRIVACY AND SECURITY!"
fi
