#!/bin/sh

# Initialize variables
SKIP_CONFIG=""
PORT=""
DOMAIN=""
CONFIG_FILE=""
BUILD_ONLY=0
PLATFORM="linux"
BUILD_OUTPUT="qgato"

# Parse arguments
while [ $# -gt 0 ]; do
  case $1 in
    --port)
      PORT=$2
      shift 2
      ;;
    --domain)
      DOMAIN=$2
      shift 2
      ;;
    --config)
      CONFIG_FILE=$2
      shift 2
      ;;
    --platform)
      PLATFORM=$2
      shift 2
      ;;
    --build-only)
      BUILD_ONLY=1
      shift
      ;;
    --skip-config-check)
      SKIP_CONFIG="--skip-config-check"
      shift
      ;;
    *)
      echo "Unknown argument: $1"
      exit 1
      ;;
  esac
done

# Get the directory of the script
SCRIPT_DIR=$(dirname "$0")

# Set GOOS and output filename
if [ "$PLATFORM" = "windows" ]; then
  GOOS=windows
  BUILD_OUTPUT="qgato.exe"
else
  GOOS=linux
  BUILD_OUTPUT="qgato"
fi

# Clean and build
echo "Cleaning previous build..."
rm -f "$SCRIPT_DIR/$BUILD_OUTPUT"

echo "Building application for $PLATFORM..."
GOOS=$GOOS go build -ldflags="-s -w" -o "$SCRIPT_DIR/$BUILD_OUTPUT" .
if [ $? -eq 0 ]; then
  echo "Build successful! Output: $SCRIPT_DIR/$BUILD_OUTPUT"
else
  echo "Build failed!"
  exit 1
fi

# Skip execution if build-only
if [ "$BUILD_ONLY" -eq 1 ]; then
  exit 0
fi

# Construct the run command
CMD="$SCRIPT_DIR/$BUILD_OUTPUT $SKIP_CONFIG"
[ -n "$PORT" ] && CMD="$CMD --port $PORT"
[ -n "$DOMAIN" ] && CMD="$CMD --domain $DOMAIN"
[ -n "$CONFIG_FILE" ] && CMD="$CMD --config $CONFIG_FILE"

echo "Starting application with command: $CMD"

# Run the built executable
eval $CMD