<?php require './ZZ_logintest.php'; ?>
<?php
  $seperator = "//\n";
  $q=$_GET["q"];
  
  //require './ZZ_versions.php';
  require './ZZ_webstatus.php';
  require './ZZ_readsettings.php';
  require './ZZ_readconfig.php';

  $user_setting_status = "";

  $boxtime = strtotime($SHIELD_now_time);
  $servertime = strtotime(date("H:i:s"));
  $timeerror = round(abs($servertime - $boxtime) / 60,2);
  $timeerror = number_format($timeerror, 2, '.', ',');


  if($SHIELD_state == "Running"){
    if($timeerror >= 1){
      $SHIELD_state = "Time Error";      
      $user_setting_status = $SHIELD_state . " " . $timeerror;
    }
  }
  if($SHIELD_state == "NOT RUNNING"){$user_setting_status = $SHIELD_state;}
  if($SHIELD_state == "UPDATING"){$user_setting_status = "Settings Applied";} 
  if($SHIELD_state == "Running"){$user_setting_status = " ";} 

  //if($SHIELD_wlan0 == "Scanning"){$user_setting_status = "Scanning for $ShieldSetting_05";} 
  
  $Unsaved_Settings = checkDefaultUnsaved();
  if ($Unsaved_Settings == 0) {
    $Unsaved_Settings = checkVPNUnsaved();
  }
  if ($Unsaved_Settings == 0) {
    $Unsaved_Settings = checkSysUpdateUnsaved();
  }

  $cfgstr = "";
  if($q == "W0"){
    delete_cfg();
    $command = $q;
    write_todo($command);
  }

  if ($q == 1) {
    $source = "./00_dothis.txt";
    $maxWaitTime = 5; // Maximum wait time in seconds
    $waited = 0;

    while (file_exists($source)) {
        if ($waited >= $maxWaitTime) {
            die("Timeout: File still exists after waiting for $maxWaitTime seconds.");
        }
        usleep(250000); // Sleep for 250 milliseconds (0.25 seconds)
        $waited += 0.25;
    }

    $command = "R";
    write_todo($command);
  }

  if($q == 2){
    $command = "r";
    write_todo($command);
  }

  if($q == 3){
    $command = "H";
    if ($SHIELD_apmode == "HOTSPOT:"){$command = "h";}
    write_todo($command);
  }

  if($q == 4){
    $command = "F";
    if ($SHIELD_fan == "On"){$command = "f";}
    write_todo($command);
  }

  if($q == 5){
    $cfgstr = "";
    if($ShieldSetting_01 == ""){$ShieldSetting_01 = "admin";}
    $oldpass = $ShieldSetting_01;
    $newpass = "";
    
    if (isset($_GET['02'])) {
      $newpass = $_GET['02'];
      if($newpass != ""){$oldpass = "";}
      if (isset($_GET['01'])) {
        $oldpass = $_GET['01'];
      }
    }    

    $cfgstr .= "01_user_password=" .  $oldpass . "\n";
    if($newpass != ""){
      $cfgstr .= "02_user_newpassword=" .  $newpass . "\n";
    }
    
    if (isset($_GET['03'])) {$cfgstr .= "03_wifi_state=" .         $_GET['03'] . "\n";}
    if (isset($_GET['04'])) {$cfgstr .= "04_wifi_mode=" .          $_GET['04'] . "\n";}
    if (isset($_GET['05'])) {$cfgstr .= "05_wifi_ssid_join=" .     $_GET['05'] . "\n";}
    if (isset($_GET['06'])) {$cfgstr .= "06_wifi_password_join=" . $_GET['06'] . "\n";}
    if (isset($_GET['07'])) {$cfgstr .= "07_wifi_ssid_AP=" .       $_GET['07'] . "\n";}
    if (isset($_GET['08'])) {$cfgstr .= "08_wifi_password_AP=" .   $_GET['08'] . "\n";}
    if (isset($_GET['09'])) {$cfgstr .= "09_eth_enabled=" .        $_GET['09'] . "\n";}
    if (isset($_GET['10'])) {$cfgstr .= "10_vpn_enabled=" .        $_GET['10'] . "\n";}
    if (isset($_GET['11'])) {$cfgstr .= "11_vpn_string=" .         $_GET['11'] . "\n";}
    if (isset($_GET['12'])) {$cfgstr .= "12_vpn_pingstring=" .     $_GET['12'] . "\n";}
    if (isset($_GET['13'])) {$cfgstr .= "13_vpn_nickname=" .       $_GET['13'] . "\n";}
    if (isset($_GET['14'])) {$cfgstr .= "14_vpn_email=" .          $_GET['14'] . "\n";}
    if (isset($_GET['15'])) {$cfgstr .= "15_vpn_wallet_id=" .      $_GET['15'] . "\n";}
    if (isset($_GET['16'])) {$cfgstr .= "16_vpn_port=" .           $_GET['16'] . "\n";}
    if (isset($_GET['17'])) {$cfgstr .= "17_vpn_purge=" .          $_GET['17'] . "\n";}
    if (isset($_GET['18'])) {$cfgstr .= "18_proxy_enabled_eth0=" . $_GET['18'] . "\n";}
    if (isset($_GET['19'])) {$cfgstr .= "19_proxy_enabled_wlan0=". $_GET['19'] . "\n";}
    if (isset($_GET['20'])) {$cfgstr .= "20_proxy_enabled_ap=" .   $_GET['20'] . "\n";}
    if (isset($_GET['21'])) {$cfgstr .= "21_vpn_json_post=".       $_GET['21'] . "\n";}
    if (isset($_GET['22'])) {$cfgstr .= "22_nft_index=".           $_GET['22'] . "\n";}
    if (isset($_GET['29'])) {$cfgstr .= "29_ROUTER_enabled=".     $_GET['29'] . "\n";}
    if (isset($_GET['30'])) {$cfgstr .= "30_PING_ipaddress=".     $_GET['30'] . "\n";}
    if (isset($_GET['94'])) {$cfgstr .= "94_TIMEZONE=" .           $_GET['94'] . "\n";}

    $cfgstr = str_replace('*', '', $cfgstr);
    
    write_cfg($cfgstr);
    $command = "C";
    write_todo($command);

    $user_setting_status = "Bad Password";
    if ($ShieldSetting_01 == $oldpass){
      $user_setting_status = "Settings written";
    }
  }

  $reply = array();
  $reply["SHIELD_allstates"] = $SHIELD_allstates;
  $reply["SHIELD_state"] = $SHIELD_state;
  $reply["SHIELD_now_time"] = $SHIELD_now_time;
  $reply["SHIELD_build_time"] = $SHIELD_build_time;
  $reply["SHIELD_build_date"] = $SHIELD_build_date;
  $reply["SHIELD_build_version"] = $SHIELD_build_version;
  $reply["SHIELD_wlan0_lbl"] = $SHIELD_apmode;
  $reply["SHIELD_wlan0"] = $SHIELD_wlan0;
  $reply["SHIELD_eth0"] = $SHIELD_eth0;
  $reply["SHIELD_vpn"] = $SHIELD_vpn;
  $reply["SHIELD_enc"] = $SHIELD_enc;
  $reply["SHIELD_network"] = $SHIELD_network;
  $reply["SHIELD_soctemp"] = $SHIELD_soctemp;
  $reply["SHIELD_gputemp"] = $SHIELD_gputemp;
  $reply["SHIELD_fan"] = $SHIELD_fan;
  $reply["SHIELD_testindex"] = $SHIELD_testindex;
  $reply["SHIELD_configstate"] = $SHIELD_configstate;
  $reply["SHIELD_pid"] = $SHIELD_pid;
  $reply["SHIELD_start"] = $SHIELD_start;
  $reply["SHIELD_ver_os"] = $SHIELD_ver_os;
  $reply["SHIELD_ver_vpn"] = $SHIELD_ver_vpn;
  $reply["SHIELD_vpnorport"] = $SHIELD_vpnorport;
  $reply["SHIELD_serial"] = $SHIELD_serial;
  $reply["SHIELD_atecid"] = $SHIELD_atecid;
  $reply['SHIELD_ipwlan0'] = $SHIELD_ipwlan0;
  $reply['SHIELD_wlan1'] = $SHIELD_wlan1;
  $reply['SHIELD_ipwlan1'] = $SHIELD_ipwlan1;
  $reply['SHIELD_ipeth0'] = $SHIELD_ipeth0;
  $reply['SHIELD_ippublic'] = $SHIELD_ippublic;
  $reply['SHIELD_fngrprnt'] = $SHIELD_fngrprnt;
  $reply['SHIELD_devicePUBKEY'] = $SHIELD_devicePUBKEY;
  $reply['SHIELD_ver_BL'] = $SHIELD_ver_BL;
  $reply['SHIELD_ver_FW'] = $SHIELD_ver_FW;
  $reply['SHIELD_web'] = $SHIELD_web;
  $reply['Fingerprints'] = $MyFamily;
  $reply['Country'] = $checkCountry;

  if($q == 7){
        // Initialize an array to hold the ShieldSetting key-value pairs
        $shieldSettings = array();
        // Assign specific variables to the $shieldSettings array
        $shieldSettings["AccountingEnabled"] = $accountingEnabled;
        $shieldSettings["AccountingMax"] = $accountingMax;
        $shieldSettings["AccountingStart"] = $accountingStart;
        $shieldSettings["RelayBandwidthRate"] = $relayBandwidthRate;
        $shieldSettings["ShieldSetting_00"] = $ShieldSetting_00;
        $shieldSettings["ShieldSetting_02"] = $ShieldSetting_02;
        $shieldSettings["ShieldSetting_03"] = $ShieldSetting_03;
        $shieldSettings["ShieldSetting_04"] = $ShieldSetting_04;
        $shieldSettings["ShieldSetting_05"] = $ShieldSetting_05;
        $shieldSettings["ShieldSetting_06"] = $ShieldSetting_06;
        $shieldSettings["ShieldSetting_07"] = $ShieldSetting_07;
        $shieldSettings["ShieldSetting_08"] = $ShieldSetting_08;
        $shieldSettings["ShieldSetting_09"] = $ShieldSetting_09;
        $shieldSettings["ShieldSetting_10"] = $ShieldSetting_10;
        $shieldSettings["ShieldSetting_11"] = $ShieldSetting_11;
        $shieldSettings["ShieldSetting_12"] = $ShieldSetting_12;
        $shieldSettings["ShieldSetting_13"] = $ShieldSetting_13;
        $shieldSettings["ShieldSetting_14"] = $ShieldSetting_14;
        $shieldSettings["ShieldSetting_15"] = $ShieldSetting_15;
        $shieldSettings["ShieldSetting_16"] = $ShieldSetting_16;
        $shieldSettings["ShieldSetting_17"] = $ShieldSetting_17;
        $shieldSettings["ShieldSetting_18"] = $ShieldSetting_18;
        $shieldSettings["ShieldSetting_19"] = $ShieldSetting_19;
        $shieldSettings["ShieldSetting_20"] = $ShieldSetting_20;
        $shieldSettings["ShieldSetting_21"] = $ShieldSetting_21;
        $shieldSettings["ShieldSetting_22"] = $ShieldSetting_22;
        $shieldSettings["ShieldSetting_23"] = $ShieldSetting_23;
        $shieldSettings["ShieldSetting_24"] = $ShieldSetting_24;
        $shieldSettings["ShieldSetting_25"] = $ShieldSetting_25;
        $shieldSettings["ShieldSetting_26"] = $ShieldSetting_26;
        $shieldSettings["ShieldSetting_27"] = $ShieldSetting_27;
        $shieldSettings["ShieldSetting_28"] = $ShieldSetting_28;
        $shieldSettings["ShieldSetting_29"] = $ShieldSetting_29;
        $shieldSettings["ShieldSetting_30"] = $ShieldSetting_30;
        // Add the $shieldSettings array to the $reply array under the "Settings" key
        $reply["Settings"] = $shieldSettings;
        $user_setting_status = " ";
  }
  
  $reply["user_setting_status"] = $user_setting_status;
  $reply["VER_home_css"] = $VER_home_css;
  $reply["VER_home"] = $VER_home;
  $reply["VER_css"] = $VER_index_css;
  $reply["VER_index"] = $VER_index;
  $reply["VER_info_css"] = $VER_info_css;
  $reply["VER_info"] = $VER_info;
  $reply["VER_logs_css"] = $VER_logs_css;
  $reply["VER_logs"] = $VER_logs;
  $reply["VER_settings_css"] = $VER_settings_css;
  $reply["VER_settings"] = $VER_settings;
  $reply["VER_style_css"] = $VER_style_css;
  $reply["VER_utils_js"] = $VER_utils_js;
  $reply["VER_login"] = $VER_login;
  $reply["VER_logintest"] = $VER_logintest;
  $reply["VER_readsettings"] = $VER_readsettings;
  $reply["VER_js"] = $VER_ajax_js;
  $reply["VER_ajax"] = $VER_ajax_php;
  $reply["VER_vers"] = $VER_vers;
  $reply["VER_webstatus"] = $VER_webstatus;
  $reply["VER_app"] = $VER_app;
  $reply["VER_os"] = $VER_os;
  $reply["VER_vpn"] = $VER_vpn;
  $reply["unsaved_settings"] = $Unsaved_Settings;
  $reply["didName"] = $didName;
  $reply["didId"] = $didId;
  
  if($q == 6){
    if (isset($_GET['logfile'])){
      $logname = $_GET['logfile'];
      $logBin = $_GET['logBin'];
      echo $bin;
      $logname = MakeLogName($logname, $logBin);
      if ($logname != ""){
        $reply = file_get_contents($logname);
        if ($reply == ""){$reply = "$logname is Empty or missing";}
        $reply = "LOGFILE:" . $reply;
      }
    }
    echo $reply;
    exit();
  }

  if($q == 8){
    $command = "s";
    write_todo($command);
  }

  
if ($q == 9) {
  // Delete first file
  $source = "/home/relayup/dev/html-normal/temp_vpn_config.cfg";
  if (file_exists($source)) {
      unlink($source) or die("Unable to delete file: $source");
  }

  // Delete second file
  $source = "./temp_default.cfg";
  if (file_exists($source)) {
      unlink($source) or die("Unable to delete file: $source");
  }

  // Delete folder
  $folderToDelete = "/home/relayup/dev/sysupdate/";
  if (file_exists($folderToDelete)) {
      if (deleteDirectory($folderToDelete)) {
          echo "Folder deleted successfully: $folderToDelete";
      } else {
          die("Unable to delete folder: $folderToDelete");
      }
  }
}

  if ($q == 10 || $_POST['q'] == 10) {

    
    $filePath = "./temp_vpn_config.cfg";
    $defaultContent = "RelayBandwidthRate 500 Mbits\nRelayBandwidthBurst 600 Mbits\nShutdownWaitLength 10\nMetricsPort 127.0.0.1:8080\nMetricsPortPolicy accept 127.0.0.1\nControlPort 9051\n";

    // ensureFileExists($filePath, $defaultContent);
    if (!file_exists($filePath)) {
      configureTempConfig($filePath);
    }

    // writeDefaultContent($filePath, $defaultContent);

    if (isset($_POST['fingerprints'])) {

      echo $filePath;
        // Extract and sanitize the fingerprints string from the query string
        $MyFamily = $_POST['fingerprints'];
        // You may want to perform further validation or sanitization on $fingerprints
        
        // Read the existing content of the .cfg file
        if (file_exists($filePath)) {
            $fileContent = file_get_contents($filePath);

            // Split file content into lines
            $lines = explode("\n", $fileContent);
            
            // Find the index of the last non-empty line
            $lastNonEmptyLineIndex = 0;
            for ($i = count($lines) - 1; $i >= 0; $i--) {
                if (!empty(trim($lines[$i]))) {
                    $lastNonEmptyLineIndex = $i;
                    break;
                }
            }

            if (!empty($MyFamily)) {
                // If fingerprints are not empty and there is no line in the file that begins with fingerprints
                if (!preg_match('/^MyFamily\s+.*$/m', $fileContent)) {
                    // Insert fingerprints line below the last non-empty line
                    array_splice($lines, $lastNonEmptyLineIndex + 1, 0, "MyFamily $MyFamily");
                } else {
                    // Replace or add the fingerprints line in the configuration
                    foreach ($lines as &$line) {
                        if (preg_match('/^MyFamily\s+.*$/m', $line)) {
                            $line = "MyFamily $MyFamily";
                            break;
                        }
                    }
                }
            } else {
                // Delete the fingerprints line from the configuration
                foreach ($lines as $index => &$line) {
                    if (preg_match('/^MyFamily\s+.*$/m', $line)) {
                        unset($lines[$index]);
                        break;
                    }
                }
            }
            
            // Combine lines back into file content
            $fileContent = implode("\n", $lines);
            
            // Write the modified content back to the .cfg file
            file_put_contents($filePath, $fileContent);
        }
    }

    if (isset($_GET['reboot']) && $Unsaved_Settings == 1) {
      $destination = "/home/relayup/dev/vpn_config.cfg";
      replaceFileContent($filePath, $destination);
      write_final_cfg();

      $source = "/home/relayup/dev/html-normal/temp_vpn_config.cfg";
        if (file_exists($source)) {
            unlink($source) or die("Unable to delete file: $source");
        }

        $source = "./temp_default.cfg";
        if (file_exists($source)) {
            unlink($source) or die("Unable to delete file: $source");
        }

    }
  }
  
  if ($q == 11) {

    $temp_vpn_config_str = "";

    $filePath = './temp_vpn_config.cfg';

    $defaultContent = "RelayBandwidthRate 500 Mbits\nRelayBandwidthBurst 600 Mbits\nShutdownWaitLength 10\nMetricsPort 127.0.0.1:8080\nMetricsPortPolicy accept 127.0.0.1\nControlPort 9051\n";

    // ensureFileExists($filePath, $defaultContent);
    if (!file_exists($filePath)) {
      configureTempConfig($filePath);
    }

    // if (!ensureFileExists($filePath)) {
    //   writeDefaultContent($filePath, $defaultContent);
    // }

    // Determine web accounting enabled status based on $_GET['21']
    $webAccountingEnabled = !(isset($_GET['21']) && strtolower($_GET['21']) === "disable");

    // Collect new settings from $_GET parameters
    if ($webAccountingEnabled) {
        if (isset($_GET['17'])) {
            $temp_vpn_config_str .= "AccountingMax " . $_GET['17'] . " GB\n";
        }
        if (isset($_GET['18'])) {

          if ($_GET['18'] === 'day') {
            $temp_vpn_config_str .= "AccountingStart " . $_GET['18'] . " 00:00\n";
          } else {
            $temp_vpn_config_str .= "AccountingStart " . $_GET['18'] . " 1 00:00\n";
          }
            
        }

        $temp_vpn_config_str .= "AccountingRule sum\n";
    }
    if (isset($_GET['19'])) {
        $temp_vpn_config_str .= "RelayBandwidthRate " . $_GET['19'] . " Mbits\n";
    }
    if (isset($_GET['20'])) {
        $temp_vpn_config_str .= "RelayBandwidthBurst " . $_GET['20'] . " Mbits\n";
    }
    if (isset($_GET['13'])) {
      $temp_vpn_config_str .= "Nickname " . $_GET['13'] . "\n";
    }
    if (isset($_GET['14']) || isset($_GET['15'])) {
      $contactInfoWeb = isset($_GET['14']) ? $_GET['14'] : '';
      $address = isset($_GET['15']) ? $_GET['15'] : '';
      $temp_vpn_config_str .= "ContactInfo " . trim($contactInfoWeb . " @anon: " . $address) . "\n";
  }
        $lineOffset = 2; // Starting point
        if ($accountingEnabled === "enable") {
            $lineOffset += 3; // AccountingMax, AccountingStart, AccountingRule
        }
        if ($contactInfo !== "") {
            $lineOffset += 1; // ContactInfo
        }
        if ($nickname !== "") {
            $lineOffset += 1; // Nickname
        }

    // Assume accounting is not enabled by default
    $remainingContent = '';

    if (file_exists($filePath)) {
        $fileLines = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        
        // Adjust the content based on the line offset
        if (count($fileLines) > $lineOffset) {
          $remainingContent = implode("\n", array_slice($fileLines, $lineOffset)) . "\n";
        }

    } else {
      $remainingContent = $defaultContent;
    }

    // Combine the new settings with the remaining content
    $finalContent = $temp_vpn_config_str;
    
    if (!empty($remainingContent)) {
        $finalContent .= $remainingContent;
    }


    if (file_exists($filePath)) {
      $myfile = fopen($filePath, "w") or die("Unable to open file!");
      fwrite($myfile, $finalContent);
      fclose($myfile);
    } 

    $Unsaved_Settings = checkDefaultUnsaved();
    if ($Unsaved_Settings == 0) {
      $Unsaved_Settings = checkVPNUnsaved();
    }
    if ($Unsaved_Settings == 0) {
      $Unsaved_Settings = checkVPNUnsaved();
    }
    if ($Unsaved_Settings == 0) {
      $Unsaved_Settings = checkSysUpdateUnsaved();
    }

    if (isset($_GET['reboot']) && $Unsaved_Settings == 1) {
      $destination = "/home/relayup/dev/vpn_config.cfg";
      $source = "./temp_vpn_config.cfg";
      if (file_exists($source) && file_exists($destination)) {
        replaceFileContent($source, $destination);
      }
      write_final_cfg();

      $source = "/home/relayup/dev/html-normal/temp_vpn_config.cfg";
        if (file_exists($source)) {
            unlink($source) or die("Unable to delete file: $source");
        }

        $source = "./temp_default.cfg";
        if (file_exists($source)) {
            unlink($source) or die("Unable to delete file: $source");
        }   
    }
  }

  if ($q == 12) {

    $destination = "/home/relayup/dev/vpn_config.cfg";
    $source = "./temp_vpn_config.cfg";
    if (file_exists($source) && file_exists($destination)) {
      replaceFileContent($source, $destination);
    }

    // $destination = "/home/relayup/dev/00_saved.cfg";
    // $source = "./temp_default.cfg";
    // replaceFileContent($source, $destination);
    write_final_cfg();

    $command = "C";
    write_todo($command);


    $source = "/home/relayup/dev/html-normal/temp_vpn_config.cfg";
        if (file_exists($source)) {
            unlink($source) or die("Unable to delete file: $source");
        }

        $source = "./temp_default.cfg";
        if (file_exists($source)) {
            unlink($source) or die("Unable to delete file: $source");
        }   

    
  }

  if ($q == 13) {
    $country = $_GET['country'];
    $filePath = './temp_vpn_config.cfg';

    if (!file_exists($filePath)) {
        configureTempConfig($filePath);
    }

    // Read current VPN config
    $currentContent = @file_get_contents($filePath);
    if ($currentContent === false) {
        echo "Error: Failed to read VPN configuration file";
        exit();
    }
    
    $currentContent = rtrim($currentContent);

    $lines = explode("\n", $currentContent);
    $filteredLines = array_filter($lines, function($line) {
        $line = trim($line);
        return !preg_match('/^(Entry|Middle|Exit)Nodes\s+{.*}$/', $line);
    });


    if ($country !== 'Global') {
      // Split countries by comma and format each one
      $countries = explode(',', $country);
      $formattedCountries = array_map(function($c) {
          return '{' . trim($c) . '}';
      }, $countries);
      
      // Join the formatted countries with commas
      $countryString = implode(',', $formattedCountries);
      
      $filteredLines[] = "EntryNodes " . $countryString;
      $filteredLines[] = "MiddleNodes " . $countryString;
      $filteredLines[] = "ExitNodes " . $countryString;
  }

  $filteredLines[] = "";

    // Write back to file
    $newContent = implode("\n", $filteredLines);
    if (@file_put_contents($filePath, $newContent) === false) {
        echo "Error: Failed to write to VPN configuration file";
        exit();
    }

    $Unsaved_Settings = checkDefaultUnsaved();
    if ($Unsaved_Settings == 0) {
        $Unsaved_Settings = checkVPNUnsaved();
    }
    if ($Unsaved_Settings == 0) {
        $Unsaved_Settings = checkSysUpdateUnsaved();
    }
}

  header('Content-Type: application/json');
  echo json_encode($reply);
  exit;

  function MakeLogName($fn, $bin) {
    if ($fn == 0) {
        return "/var/log/bootstrap.log";
    } else if ($fn == 1) {
        return "/var/log/" . $bin . "/notices.log";
    } else if ($fn == 2) {
        return "/home/relayup/dev/logs/00_logs.log";
    } else {
        return "";
    }
}



  function write_todo($dothis){
    $myfile = fopen("./00_dothis.txt", "w") or die("Unable to open file!");
    fwrite($myfile, $dothis);
    fclose($myfile);  
  }

  function delete_cfg(){
    $settingfile = "./temp_default.cfg";
    if (file_exists($settingfile)) { 
      unlink($settingfile);
    }
  }

  function write_cfg($dothiscfg){
    $settingfile = "./temp_default.cfg";
    $myfile = fopen($settingfile, "w") or die("Unable to open file!");
    fwrite($myfile, $dothiscfg);
    fclose($myfile);  
  }

  function ensureFileExists($filePath, $defaultContent) {
    if (!file_exists($filePath)) {
        $myfile = fopen($filePath, "w") or die("Unable to open file!");
        fwrite($myfile, $defaultContent);
        fclose($myfile);
    }
  }

  function deleteDirectory($dir) {
      if (!file_exists($dir)) {
          return true;
      }

      if (!is_dir($dir)) {
          return unlink($dir);
      }

      foreach (scandir($dir) as $item) {
          if ($item == '.' || $item == '..') {
              continue;
          }

          if (!deleteDirectory($dir . DIRECTORY_SEPARATOR . $item)) {
              return false;
          }
      }

      return rmdir($dir);
  }


  // function write_final_cfg() {
  //   $tempSettingFile = "./temp_default.cfg";
  //   $finalSettingFile = "../00_websaved.cfg";
    
  //   // Check if the temp_default.cfg file exists
  //   if (!file_exists($tempSettingFile)) {
  //       die("temp_default.cfg file does not exist!");
  //   }

  //   // Read content from temp file
  //   $content = file_get_contents($tempSettingFile);
  //   if ($content === false) {
  //       die("Unable to read from temp_default.cfg!");
  //   }

  //   // Write content to new file
  //   if (file_put_contents($finalSettingFile, $content) === false) {
  //       die("Unable to write to 00_websaved.cfg!");
  //   }
  // }


  function write_final_cfg() {
    $tempSettingFile = "./temp_default.cfg";
    $finalSettingFile = "./default.cfg";
    
    // Check if the temp_default.cfg file exists
    if (!file_exists($tempSettingFile)) {
        die("temp_default.cfg file does not exist!");
    }

    // Rename temp_default.cfg to default.cfg
    if (!rename($tempSettingFile, $finalSettingFile)) {
        die("Unable to rename temp_default.cfg to default.cfg!");
    }
  }


  function append_cfg($dothiscfg){
    $settingfile = "./temp_default.cfg";
    if (file_exists($settingfile)) { 
      $myfile = fopen($settingfile, "a") or die("Unable to open file!");
    } else {
      $myfile = fopen($settingfile, "w") or die("Unable to open file!");
    }
    fwrite($myfile, $dothiscfg);
    fclose($myfile);  
  }

  function parseConfig($filename) {
    $data = file($filename, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    $config = [];

    foreach ($data as $line) {
        list($key, $value) = explode('=', $line, 2);
        $config[$key] = $value;
    }

    return $config;
  }

  function configureTempConfig($TEMPfilePath) {
    $vpnConfigFile = "/home/relayup/dev/vpn_config.cfg";
      $contents = file_get_contents($vpnConfigFile);
      if ($contents === false) {
          die("Error reading from $vpnConfigFile");
      }
      // Write the contents to temp_vpn_config.cfg
      $result = file_put_contents($TEMPfilePath, $contents);
      if ($result === false) {
          die("Error writing to $TEMPfilePath");
      } else {
          echo "Contents of $TEMPfilePath have been replaced successfully.";
      }
  }

  function getNumericPrefix($key) {
    return substr($key, 0, 2);
  }

  function checkDefaultUnsaved() {

    $temp_file = "./temp_default.cfg";
    $perm_file = "/home/relayup/dev/00_saved.cfg";

    $temp_config = parseConfig($temp_file);
    $perm_config = parseConfig($perm_file);

    foreach ($perm_config as $permKey => $permValue) {
      $prefix = getNumericPrefix($permKey);
  
      // Find the corresponding key in the default config
      foreach ($temp_config as $tempKey => $tempValue) {
        if (getNumericPrefix($tempKey) === '02') {
          return 1;
          break;
        }
        if (getNumericPrefix($tempKey) === $prefix) {
          // Compare values
          if ($permValue !== $tempValue) {
            // Values are not the same
            return 1;
            break;
          }
        }
      }
    }

    return 0;
  }

  function checkVPNUnsaved() {

    $file1 = "./temp_vpn_config.cfg";
    $file2 = "/home/relayup/dev/vpn_config.cfg";

    if (!file_exists($file1)) {
      return 0;
    }

    // Read the contents of both files into arrays
    $content1 = file($file1, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    $content2 = file($file2, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

    // Remove empty lines
    $content1 = array_filter($content1, 'strlen');
    $content2 = array_filter($content2, 'strlen');

    // Compare the contents of the two files
    if ($content1 === $content2) {
        return 0;
    } else {
        return 1;
    }
  }

  function checkSysUpdateUnsaved() {
    $folderPath = '/home/relayup/dev/sysupdate/';

    // Check if the folder doesn't exist
    if (!file_exists($folderPath)) {
        return 0;
    }

    // Check if it's not a directory
    if (!is_dir($folderPath)) {
        return 1; // It exists but it's not a directory
    }

    // Get the contents of the directory
    $contents = scandir($folderPath);

    // Remove '.' and '..' from the list
    $contents = array_diff($contents, array('.', '..'));

    // If the directory is empty (contains no files or subdirectories)
    if (empty($contents)) {
        return 0;
    }

    // The folder exists and is not empty
    return 1;
}



  function writeDefaultContent($filePath, $defaultContent) {

    // Check if the VPN configuration file exists and is not empty
    if (!file_exists($filePath) || filesize($filePath) === 0) {
      // Attempt to open the file for writing, exit with an error message if unsuccessful
      $fileHandle = fopen($filePath, "w") or die("Unable to open file: $filePath");
      
      // Write the default content to the file
      fwrite($fileHandle, $defaultContent);
      
      // Close the file handle
      fclose($fileHandle);
      
      // Set the file permissions, exit with an error message if unsuccessful
      chmod($filePath, 0644) or die("Unable to set file permissions for $filePath");
    }

  }

  

  function replaceFileContent($sourceFile, $destinationFile) {
    // Check if the source file exists
    if (!file_exists($sourceFile)) {
        die("Source file does not exist.");
    }

    if (!file_exists($destinationFile)) {
      die("destination file does not exist.");
  }

    // Read the content from the source file
    $sourceContent = file_get_contents($sourceFile);

    // Check if reading the content was successful
    if ($sourceContent === false) {
        die("Failed to read from the source file.");
    }

    // Write the content to the destination file, replacing its content
    $writeResult = file_put_contents($destinationFile, $sourceContent);

    // Check if writing the content was successful
    if ($writeResult === false) {
        die("Failed to write to the destination file.");
    }

    echo "Content successfully replaced in the destination file.";
  }
?>