# -----------------------------------------------
# ProVide Server under Wine (headless, multi-arch safe)
# -----------------------------------------------

# Multi-arch Wine base (x86_64 + ARM64 via QEMU)
FROM scottyhardy/docker-wine:stable

# -----------------------------------------------
# Base environment
# -----------------------------------------------
WORKDIR /var/provide
ENV LANG=en_US.UTF-8 \
    LANGUAGE=en_US:en \
    LC_ALL=en_US.UTF-8 \
    XDG_RUNTIME_DIR=/tmp/runtime-wine \
    DISPLAY=:0 \
    WINEDEBUG=-all,+warn,+err

# -----------------------------------------------
# Install minimal dependencies
# -----------------------------------------------
RUN apt-get update -qq && \
    DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
      ftp netcat-openbsd curl && \
    rm -rf /var/lib/apt/lists/*

RUN mkdir -p "$XDG_RUNTIME_DIR" && chmod 700 "$XDG_RUNTIME_DIR"

# -----------------------------------------------
# Graceful shutdown helper
# -----------------------------------------------
RUN cat <<'EOF' > /usr/local/bin/shutdown_provide.sh
#!/bin/bash
set -e

HOST=127.0.0.1
PORT=${PROVIDE_PORT}
USER=${PROVIDE_SHUTDOWN_USER}
PASS=${PROVIDE_SHUTDOWN_PASS}

# Wait for API to be ready
for i in {1..10}; do
  RESPONSE=$(ftp -inv "$HOST" "$PORT" <<EOF2 2>&1
user $USER $PASS
quote NOOP
bye
EOF2
)
  if echo "$RESPONSE" | grep -q "230 "; then
    READY=true
    break
  fi
  echo "[WAIT] Waiting for ProVide API... ($i/10)"
  sleep 6
done

# If API didn't respond, force termination
if [[ "$READY" != "true" ]]; then
  echo "[WARN] No API response - forcing shutdown."
  pkill -TERM wine* || true
  wait
  exit 0
fi

# Send shutdown via a raw TCP session to avoid protocol issues
{
  exec 3<>/dev/tcp/$HOST/$PORT || exit 1
  read -r _ <&3 || true
  echo "USER $USER" >&3; read -r _ <&3 || true
  echo "PASS $PASS" >&3; read -r resp <&3 || true
  [[ "$resp" == 230* ]] || echo "[WARN] Auth failed: ${resp:-none}"
  echo "SHUTDOWN" >&3; read -r _ <&3 || true
} || true

echo "[INFO] Flushing filesystem buffers..."
sync
sleep 1
EOF
RUN chmod +x /usr/local/bin/shutdown_provide.sh

# -----------------------------------------------
# Entrypoint script
# -----------------------------------------------
RUN cat <<'EOF' > /entrypoint.sh
#!/bin/bash
set -e

log() { echo "[$(date +%FT%T%z)] $*"; }

cleanup() {
  log "SIGTERM received — initiating graceful shutdown."
  /usr/local/bin/shutdown_provide.sh || true
  log "Flushing filesystem buffers..."
  sync
  sleep 1
  log "Cleanup complete."
  exit 0
}

trap cleanup SIGTERM SIGINT

mkdir -p "$XDG_RUNTIME_DIR" && chmod 700 "$XDG_RUNTIME_DIR"

log "Starting ProVide Server under Wine..."
wine ./ProVide.exe /wine &
APP_PID=$!

wait $APP_PID || true
EOF
RUN chmod +x /entrypoint.sh

# -----------------------------------------------
# Expose selected ports
# -----------------------------------------------
EXPOSE 8443 62222 62243

ENTRYPOINT ["/entrypoint.sh"]
