#!/bin/bash

set -e

CONTAINER_NAME="${CONTAINER_NAME:-pmon}"
INSTALL_DIR="/tmp/mdsi-transceiver-tools"

echo "MDSI Transceiver Tools - PMON Container Installer"
echo "=================================================="
echo ""

if [ ! -f "setup.py" ]; then
    echo "Error: Must run from mdsi-transceiver-tools root directory"
    exit 1
fi

echo "Checking if $CONTAINER_NAME container is running..."
if ! docker ps | grep -q "$CONTAINER_NAME"; then
    echo "Error: $CONTAINER_NAME container is not running"
    exit 1
fi

echo "Creating distribution package..."
python3 setup.py sdist

TARBALL=$(ls -t dist/*.tar.gz | head -1)
if [ -z "$TARBALL" ]; then
    echo "Error: Failed to create distribution package"
    exit 1
fi

echo "Copying package to $CONTAINER_NAME container..."
docker cp "$TARBALL" "$CONTAINER_NAME:$INSTALL_DIR.tar.gz"

echo "Installing in $CONTAINER_NAME container..."
docker exec "$CONTAINER_NAME" bash -c "
    cd /tmp && \
    tar xzf $INSTALL_DIR.tar.gz && \
    cd mdsi-transceiver-tools-* && \
    pip3 install -e . && \
    echo 'Installation complete!'
"

echo ""
echo "Verifying installation..."
docker exec "$CONTAINER_NAME" mdsi-transceiver --version

echo ""
echo "Installation successful!"
echo ""
echo "Usage:"
echo "  docker exec -it $CONTAINER_NAME bash"
echo "  mdsi-transceiver show --port Ethernet0"
echo ""
