#!/usr/bin/env bash
# run.sh — Build and run the OST-to-PST converter without docker-compose
set -e

IMAGE="ost2pst:latest"
CONTAINER="ost2pst"
PORT="${PORT:-3000}"

# ── Ensure converted output directory exists on the host ─────────────────────
mkdir -p "$(pwd)/converted"

# ── Stop + remove any existing container ─────────────────────────────────────
if [ "$(docker ps -aq -f name=^/${CONTAINER}$)" ]; then
    echo "Stopping existing container..."
    docker stop "$CONTAINER" >/dev/null 2>&1 || true
    docker rm   "$CONTAINER" >/dev/null 2>&1 || true
fi

# ── Build (skipped automatically if image is up-to-date) ─────────────────────
echo "Building image $IMAGE ..."
docker build -t "$IMAGE" .

# ── Run ───────────────────────────────────────────────────────────────────────
echo "Starting $CONTAINER on http://localhost:${PORT} ..."
docker run -d \
    --name "$CONTAINER" \
    --restart unless-stopped \
    -p "${PORT}:3000" \
    -v "$(pwd)/converted:/app/converted" \
    "$IMAGE"

echo ""
echo "✅  Converter is running at: http://localhost:${PORT}"
echo "    Converted files will appear in: $(pwd)/converted/"
echo ""
echo "    To stop:   docker stop $CONTAINER"
echo "    To logs:   docker logs -f $CONTAINER"
