#!/usr/bin/env bash

set -e

# Check if Docker daemon is running
if ! docker info >/dev/null 2>&1; then
    echo "Error: Docker daemon is not running"
    exit 1
fi

IMAGE_NAME="markdownblog"
CONTAINER_NAME="markdownblog"
VOLUME_NAME="markdownblog-posts"
PORT="8080"

# Stop and remove any containers using the volume
VOLUME_CONTAINERS=$(docker ps -a --filter volume=$VOLUME_NAME -q)
if [ -n "$VOLUME_CONTAINERS" ]; then
  echo "Stopping and removing containers using the volume..."
  docker rm -f $VOLUME_CONTAINERS
fi

# Remove the volume for a clean start (optional, comment out if you want to keep posts)
echo "Removing Docker volume (for a clean start)..."
docker volume rm $VOLUME_NAME 2>/dev/null || true

echo "Building Docker image..."
docker build -t $IMAGE_NAME .

echo "Running new container with persistent volume..."
docker run -d \
  --name $CONTAINER_NAME \
  -p $PORT:3000 \
  -v $VOLUME_NAME:/app/docker \
  $IMAGE_NAME

# Copy built-in posts to the volume if it's empty (one-time init)
echo "Copying built-in posts to Docker volume if empty..."
docker exec $CONTAINER_NAME sh -c 'if [ -d /app/posts ] && [ -d /app/docker ] && [ "$(ls -A /app/docker)" = "" ]; then cp -r /app/posts/* /app/docker/; fi'

# Check if container is running
if ! docker ps | grep -q $CONTAINER_NAME; then
    echo "Error: Container failed to start. Check logs with: docker logs $CONTAINER_NAME"
    exit 1
fi

echo "Deployment complete!"
echo "App should be available at http://localhost:$PORT"
