#!/bin/bash -e
#
# This file is part of AtomVM.
#
# Copyright 2023 Fred Dushin <fred@dushin.net>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0 OR LGPL-2.1-or-later
#

readonly root="$(cd $(dirname $0)/.. && pwd)"
readonly root_bin="${root}/bin"

if [ -z "${_ATOMVM_SMOKE}" ]; then
    cat > "${root_bin}/activate" << EOF
#!/usr/bin/env false

## This file was generated by the "${root_bin}/relocate script on $(date)"

. "${root}/etc/esp32.sh"

echo
echo "Enter any changes to default settings (hit enter to accept defaults)"
echo "===================================================================="
echo -n "ESP32_PORT [/dev/ttyUSB0]> "; read
if [ -n "\${REPLY}" ]; then
    export ESP32_PORT="\${REPLY}"
fi
echo -n "ESP32_BAUD [921600]> "; read
if [ -n "\${REPLY}" ]; then
    export ESP32_BAUD="\${REPLY}"
fi
echo -n "ESP32_ESPTOOL [esptool.py]> "; read
if [ -n "\${REPLY}" ]; then
    export ESP32_ESPTOOL="\${REPLY}"
fi
echo -n "ESP32_CHIP [auto]> "; read
if [ -n "\${REPLY}" ]; then
    export ESP32_CHIP="\${REPLY}"
fi
echo -n "ESP32_OFFSET [0x1000]> "; read
if [ -n "\${REPLY}" ]; then
    export ESP32_OFFSET="\${REPLY}"
fi

# Set equivalents for rebar3 plugin (Do not set ATOMVM_REBAR3_PLUGIN_ESP32_OFFSET)
export ATOMVM_REBAR3_PLUGIN_ESP32_FLASH_ESPTOOL="\${ESP32_ESPTOOL}"
export ATOMVM_REBAR3_PLUGIN_ESP32_FLASH_CHIP="\${ESP32_CHIP}"
export ATOMVM_REBAR3_PLUGIN_ESP32_FLASH_PORT="\${ESP32_PORT}"
export ATOMVM_REBAR3_PLUGIN_ESP32_FLASH_BAUD="\${ESP32_BAUD}"

export PS1="[atomvm-smoke] \${PS1:-}"

export PATH="${root_bin}:\${PATH}"

echo "=================================="
echo
echo "'${root_bin}' has been added to your PATH environment variable."

echo
echo "The following variables have been added to your environment:"
echo
env | grep ESP32
env | grep _ATOMVM_SMOKE

echo
echo "You are now ready for smoke testing AtomVM.  Good luck!"
echo

EOF

    chmod 644 "${root_bin}/activate"
    export ATOMVM_SMOKE=1

    echo "%%"
    echo "%% Created '${root_bin}/activate' script."
    echo "%%"
    echo "%% Source this file to start smoke testing."
    echo "%%"
    echo "%% Example:"
    echo "%%"
    echo "%%     shell$ . '${root_bin}/activate'"
    echo "%%"

else
    echo "_ATOMVM_SMOKE already activated"
fi
