#!/usr/bin/env bash

# expected inputs:
# TREZOR_SRC -- directory containing python code for uMP

if [[ ! "${TREZOR_SRC}" ]]; then echo "expecting TREZOR_SRC"; exit 0; fi

# optional inputs:
# TREZOR_PROFILE -- profile name (directory) in ~/.trezoremu or full path
# TREZOR_PROFILING -- wrap the uMP/python in the profiler script

# outputs:
## uMP
#   PYOPT
#   HEAPSIZE
#   ARGS -- uMP arguments
#   MAIN -- uMP file to execute
## Trezor core
#   TREZOR_PROFILE_DIR
#   TREZOR_PROFILE_NAME
#   TREZOR_UDP_PORT
## this script
#   TREZOR_SRC
#   TREZOR_LOGFILE
## python-trezor
#   TREZOR_PATH -- connect string


# defaults
PYOPT="${PYOPT:-1}"
HEAPSIZE="${HEAPSIZE:-20M}"

TREZOR_PROFILE="${TREZOR_PROFILE:-/var/tmp}"
TREZOR_PROFILE_DIR="${TREZOR_PROFILE}"
TREZOR_PROFILE_NAME="${TREZOR_PROFILE}"

# for profile names create profile directory if not existent
if ! [[ "$TREZOR_PROFILE" == "/"* ]]; then
    TREZOR_PROFILE_DIR="${HOME}/.trezoremu/${TREZOR_PROFILE}"
    if ! [[ -d "${TREZOR_PROFILE_DIR}" ]]; then
        mkdir -p "${TREZOR_PROFILE_DIR}"
        PORT=$(( ( RANDOM % 1000 )  + 1 + 21324 ))
        echo "# autogenerated config" > "${TREZOR_PROFILE_DIR}/emu.config"
        echo "TREZOR_UDP_PORT=\"\${TREZOR_UDP_PORT:-${PORT}}\"" >> "${TREZOR_PROFILE_DIR}/emu.config"
    fi
fi

# load profile config
if [[ -f "${TREZOR_PROFILE_DIR}/emu.config" ]]; then
    source "${TREZOR_PROFILE_DIR}/emu.config"
fi

# for profiling wrap
if [[ "$TREZOR_PROFILING" -gt 0 ]]; then
    MAIN="${TREZOR_SRC}/../prof/prof.py"
else
    MAIN="${TREZOR_SRC}/main.py"
fi

TREZOR_LOGFILE="${TREZOR_PROFILE_DIR}/trezor.log"
TREZOR_UDP_PORT="${TREZOR_UDP_PORT:-21324}"
TREZOR_PATH="${TREZOR_PATH:-udp:127.0.0.1:${TREZOR_UDP_PORT}}"

echo "Trezor^emu profile name: ${TREZOR_PROFILE_NAME}"
echo "Trezor^emu profile directory: ${TREZOR_PROFILE_DIR}"
echo "Trezor^emu log file: ${TREZOR_LOGFILE}"
echo "Trezor^emu UDP port: ${TREZOR_UDP_PORT}"
echo "Trezor^emu path: ${TREZOR_PATH}"
echo "Trezor^emu src: ${TREZOR_SRC}"

export TREZOR_PROFILE_NAME="${TREZOR_PROFILE_NAME}"
export TREZOR_PROFILE_DIR="${TREZOR_PROFILE_DIR}"
export TREZOR_LOGFILE="${TREZOR_LOGFILE}"
export TREZOR_UDP_PORT="${TREZOR_UDP_PORT}"
export TREZOR_PATH="${TREZOR_PATH}"
export TREZOR_SRC="${TREZOR_SRC}"

ARGS="-O${PYOPT} -X heapsize=${HEAPSIZE}"
