#!/bin/bash

# BuildKit daemon management script for macOS development

case "$1" in
    start)
        echo "Starting BuildKit daemon..."
        docker stop buildkitd 2>/dev/null || true
        docker rm buildkitd 2>/dev/null || true
        
        # Create buildkit config if it doesn't exist
        if [ ! -f buildkitd.toml ]; then
            cat > buildkitd.toml << EOF
# BuildKit configuration for insecure registries

[registry."host.docker.internal:5000"]
  http = true
  insecure = true

[registry."localhost:5000"]
  http = true
  insecure = true
EOF
        fi
        
        docker run -d -p 1234:1234 --name buildkitd \
            --add-host host.docker.internal:host-gateway \
            -v "$(pwd)/buildkitd.toml:/etc/buildkit/buildkitd.toml:ro" \
            --privileged moby/buildkit:latest \
            --allow-insecure-entitlement="security.insecure" \
            --allow-insecure-entitlement="network.host" \
            --addr tcp://0.0.0.0:1234 \
            --config /etc/buildkit/buildkitd.toml
        echo "BuildKit daemon started on tcp://127.0.0.1:1234 with insecure registry support"
        ;;
    stop)
        echo "Stopping BuildKit daemon..."
        docker stop buildkitd
        docker rm buildkitd
        echo "BuildKit daemon stopped"
        ;;
    status)
        echo "BuildKit daemon status:"
        docker ps -a | grep buildkitd || echo "BuildKit daemon is not running"
        ;;
    logs)
        echo "BuildKit daemon logs:"
        docker logs buildkitd
        ;;
    restart)
        $0 stop
        sleep 2
        $0 start
        ;;
    *)
        echo "Usage: $0 {start|stop|status|logs|restart}"
        echo ""
        echo "Commands:"
        echo "  start   - Start BuildKit daemon container"
        echo "  stop    - Stop and remove BuildKit daemon container"
        echo "  status  - Show BuildKit daemon status"
        echo "  logs    - Show BuildKit daemon logs"
        echo "  restart - Restart BuildKit daemon"
        exit 1
        ;;
esac
