#!/bin/bash

# Script to launch the GSM Simulator in Docker

# Variables
IMAGE_NAME="gsm-simulator"
CONTAINER_NAME="gsm-sim"
PORT="5555"

# Check if Docker is installed
if ! command -v docker &> /dev/null; then
    echo "Error: Docker is not installed. Please install Docker and try again."
    exit 1
fi

# Check if the gsm_simulator.py file exists in the current directory
if [ ! -f "gsm_simulator.py" ]; then
    echo "Error: gsm_simulator.py not found in the current directory."
    echo "Please ensure gsm_simulator.py is present and try again."
    exit 1
fi

# Create Dockerfile if it doesn't exist
if [ ! -f "Dockerfile" ]; then
    echo "Creating Dockerfile..."
    cat <<EOF > Dockerfile
FROM python:3.9-slim
WORKDIR /app
COPY gsm_simulator.py /app
CMD ["python", "gsm_simulator.py"]
EOF
fi

# Build the Docker image
echo "Building Docker image: $IMAGE_NAME..."
docker build -t $IMAGE_NAME .

# Check if the build was successful
if [ $? -ne 0 ]; then
    echo "Error: Failed to build Docker image."
    exit 1
fi

# Stop and remove any existing container with the same name
if [ "$(docker ps -q -f name=$CONTAINER_NAME)" ]; then
    echo "Stopping existing container: $CONTAINER_NAME..."
    docker stop $CONTAINER_NAME
fi
if [ "$(docker ps -aq -f name=$CONTAINER_NAME)" ]; then
    echo "Removing existing container: $CONTAINER_NAME..."
    docker rm $CONTAINER_NAME
fi

# Run the Docker container
echo "Launching GSM Simulator in Docker container: $CONTAINER_NAME..."
docker run -d -p $PORT:$PORT --name $CONTAINER_NAME $IMAGE_NAME

# Check if the container is running
if [ $? -eq 0 ]; then
    echo "GSM Simulator is running on port $PORT."
    echo "Container ID: $(docker ps -q -f name=$CONTAINER_NAME)"
    echo "You can now connect your external Python programs to localhost:$PORT."
else
    echo "Error: Failed to launch the container."
    exit 1
fi