<?php
// Define a constant to indicate index.php is included, not accessed directly
define('FILE_IS_INCLUDED', true);

// Include the index.php file, which contains shared configuration and logic
include('index.php');

// Only allow this script to run from the command line interface
if (php_sapi_name() !== 'cli') {
  error_deny();  // Deny access if run from a browser or non-CLI environment
}

/**
 * This script checks environment integrity:
 * - Verifies required constants
 * - Validates directory and file permissions
 * - Creates required files if missing
 * - Verifies JSON syntax
 */

echo "== ip2nginx Environment Check ==\n";

// List of required files with their default content and persistence flag
$requiredFiles = [
  TOKENFILE      => ['default' => DEF_EXAMPLE, 'keep' => true],
  METAFILE       => ['default' => [], 'keep' => false],
  LOGFILE        => ['default' => [], 'keep' => false],
  BLOCKLIST_FILE => ['default' => [], 'keep' => false],
  FAILURESFILE   => ['default' => [], 'keep' => false],
];

// Check if DATA_DIR exists and is writable
echo "- DATA_DIR: " . DATA_DIR . "\n";
if (!is_dir(DATA_DIR)) {
  echo "  ❌ DATA_DIR does not exist\n";
} elseif (!is_writable(DATA_DIR)) {
  echo "  ⚠️ DATA_DIR is not writable\n";
} else {
  echo "  ✅ DATA_DIR OK\n";
}

// Check and optionally create required files
foreach ($requiredFiles as $file => $opts) {
  echo "- Checking: $file\n";
  if (!file_exists($file)) {
    echo "  ⚠️ File not found. Creating...\n";
    saveJson($file, $opts['default']);
  } else {
    $opts['keep'] = true;
  }

  if (!file_exists($file)) {
    echo "  ❌ Failed to create\n";
    continue;
  }

  if (!is_readable($file)) {
    echo "  ⚠️ Not readable\n";
    continue;
  }

  if (!is_writable($file)) {
    echo "  ⚠️ Not writable\n";
    continue;
  }

  // Validate JSON syntax
  loadJson($file);
  if (json_last_error() !== JSON_ERROR_NONE) {
    echo "  ❌ Invalid JSON: " . json_last_error_msg() . "\n";
  } else {
    echo "  ✅ JSON valid\n";
  }

  if (!$opts['keep']) {
    echo  "  ℹ️ Will be auto-deleted\n";
    unlink($file);
  }
}

// Check NGINX conf directory
echo "- NGINX base: " . VHOST_BASE . "\n";
if (!is_dir(VHOST_BASE)) {
  echo "  ❌ VHOST_BASE directory missing\n";
} elseif (!is_readable(VHOST_BASE)) {
  echo "  ⚠️ VHOST_BASE not readable\n";
} else {
  echo "  ✅ VHOST_BASE OK\n";
}

echo "Check complete.\n";
