#!/bin/bash
#
# BASH
#
# Copyright 2024-2025 MicroEJ Corp. All rights reserved.
# MicroEJ Corp. PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.

# 'build.sh' is responsible for producing the executable file 
# then copying this executable file to the current directory where it has been executed to a file named 'application.out'

set -e

# Detect architecture
ARCH=$(uname -m)

# Determine platform
if [[ "$ARCH" == "x86_64" ]]; then
    PLATFORM="linux/amd64"
elif [[ "$ARCH" == "arm64" || "$ARCH" == "aarch64" ]]; then
    PLATFORM="linux/arm64"
else
    echo "Unsupported architecture: $ARCH"
    exit 1
fi

# Determine directory paths
EXECUTION_DIR=$(pwd)
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BSP_DIR="$(cd "${SCRIPT_DIR}/../../" && pwd)"
ROOT_DIR="$(cd "${BSP_DIR}/../" && pwd)"

# Determine Docker names
IMAGE_NAME="actions-vee-port:latest"
CONTAINER_NAME="Actions-VEE-Port-Container"

# If we are currently in a docker environment, just call build_.sh
if [ -f "/.dockerenv" ] || [ -f "$HOME/.dockerenv" ]; then
    bash ${SCRIPT_DIR}/build_.sh
else
    # Check if the image exists
    if ! docker images --format '{{.Repository}}:{{.Tag}}' | grep -q "^${IMAGE_NAME}$"; then
        echo "${IMAGE_NAME} Image does not exist. Creating the image..."
        docker build -t ${IMAGE_NAME} --platform="$PLATFORM" -f ${SCRIPT_DIR}/docker/Dockerfile ${SCRIPT_DIR}/docker
    fi

    # Check if the container exists
    if [ "$(docker ps -a -q -f name=^/${CONTAINER_NAME}$)" ]; then
        docker start $CONTAINER_NAME
    else
        echo "${CONTAINER_NAME} Container does not exist. Creating the container..."
        docker run -i -d --name $CONTAINER_NAME \
                -v${ROOT_DIR}:${ROOT_DIR} \
                -v${EXECUTION_DIR}:${EXECUTION_DIR} -w${EXECUTION_DIR} \
                --platform "$PLATFORM" \
                "${IMAGE_NAME}" 
    fi
    docker exec -i $CONTAINER_NAME bash ${SCRIPT_DIR}/build_.sh
fi

cp -v ${SCRIPT_DIR}/../../core/outdir/ats3085s_dev_watch_ext_nor/zephyr/zephyr.elf ${SCRIPT_DIR}/application.out
cp -v ${SCRIPT_DIR}/../../core/outdir/ats3085s_dev_watch_ext_nor/zephyr/zephyr.elf ${EXECUTION_DIR}/application.out

# Find the latest .fw file in the source directory based on modification date
latestFile=$(ls -t ${SCRIPT_DIR}/../../core/outdir/ats3085s_dev_watch_ext_nor/_firmware/*.fw | head -n 1)

# Check if we found a file
if [ -n "$latestFile" ]; then
    echo "Latest file: $latestFile"
else
    echo "No .fw files found!"
    exit
fi

cp -v ${latestFile} ${SCRIPT_DIR}/application.fw
cp -v ${latestFile} ${EXECUTION_DIR}/application.fw
