{ pkgs, ... }:

pkgs.writeShellScriptBin "mcrcon" ''
  set -euo pipefail

  # Configuration - can be overridden with environment variables
  MINECRAFT_RCON_HOST="''${MCRCON_HOST:-10.0.0.165}"
  MINECRAFT_RCON_PORT="''${MCRCON_PORT:-25575}"
  RBW_ENTRY="minecraft-rcon"

  # Check if rbw is available
  if ! command -v rbw &> /dev/null; then
    echo "Error: rbw is not available. Please ensure rbw is installed and configured."
    exit 1
  fi

  # Retrieve password from Bitwarden
  if ! MCRCON_PASS=$(rbw get "$RBW_ENTRY" 2>/dev/null); then
    echo "Error: Failed to retrieve RCON password from rbw entry '$RBW_ENTRY'"
    echo "Please ensure the entry exists in Bitwarden and rbw is synced."
    echo ""
    echo "To create the entry:"
    echo "  1. Add 'minecraft-rcon' to Bitwarden with the RCON password"
    echo "  2. Run 'rbw sync' to refresh the local cache"
    exit 1
  fi

  # Export for mcrcon
  export MCRCON_HOST="$MINECRAFT_RCON_HOST"
  export MCRCON_PORT="$MINECRAFT_RCON_PORT"
  export MCRCON_PASS

  # If no arguments provided, start interactive terminal mode
  if [[ $# -eq 0 ]]; then
    exec ${pkgs.mcrcon}/bin/mcrcon -t
  fi

  # Execute mcrcon with all provided arguments
  exec ${pkgs.mcrcon}/bin/mcrcon "$@"
''
