<?php require './XX_logintest.php'; ?>
<?php

if (isset($_SERVER['HTTP_ORIGIN'])) {
  header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
  header('Access-Control-Allow-Credentials: true');
  header('Access-Control-Max-Age: 86400');    // cache for 1 day
}

// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

  if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
      header("Access-Control-Allow-Methods: GET, POST, OPTIONS");         

  if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
      header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

  exit(0);
}


  $seperator = "//\n";
  $q=$_GET["q"];
    
    
  //require './XX_versions.php';
  require './XX_webstatus.php';
  require './XX_readsettings.php';
  require './XX_scanwifi.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";} 
  
//****************************************************
  // delete web config = W0
  // new_password = W1
  // ethernet = W2
  // wifi = W3
  // vpn nickname,email = W4
  // wallet addr = W5
  // port = W6

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

  if($q == "W1"){
    if($ShieldSetting_01 == ""){$ShieldSetting_01 = "admin";}
    $cfgstr .= "01_user_password=" .  $ShieldSetting_01 . "\n";
    if (isset($_GET['02'])) {$cfgstr .= "02_user_newpassword=" .        $_GET['02'] . "\n";}
    $cfgstr = str_replace('*', '', $cfgstr);   
    write_cfg($cfgstr);
    write_temp_cfg($cfgstr);
    $command = $q;
    write_todo($command);
  }

  if($q == "W2"){
    // check_vpnConfig();
    $settingfile = "./default.cfg";
    if (isset($_GET['09'])) {$cfgstr .= "09_eth_enabled=" .        $_GET['09'] . "\n";}
    $cfgstr = str_replace('*', '', $cfgstr);   
    write_cfg($cfgstr);

    $command = $q;
    write_todo($command);
  }

  if($q == "W3"){
    // check_vpnConfig();

    $SSID = "";
    $cfgstr .= "23_wifi_state_Intfc_II=off\n";
    if (isset($_GET['05'])) { $SSID = $_GET['05']; }
    if($SSID == ""){
      $cfgstr .= "03_wifi_state=off\n";
      $cfgstr .= "04_wifi_mode=ap\n";
    } else {
      $cfgstr .= "03_wifi_state=on\n";
      $cfgstr .= "04_wifi_mode=join\n";
    }      
    $cfgstr .= "05_wifi_ssid_join=" . $SSID . "\n";
    if (isset($_GET['06'])) {$cfgstr .= "06_wifi_password_join=" . $_GET['06'] . "\n";}
    $cfgstr = str_replace('*', '', $cfgstr);   
    append_temp_cfg($cfgstr);
    $command = $q;
    write_todo($command);
  }

  if($q == "W3b"){
    // check_vpnConfig();
    $SSID = "";
    if (isset($_GET['05'])) { $SSID = $_GET['05']; }
    if($SSID == ""){ // Ethernet
      $cfgstr .= "03_wifi_state=off\n";
      $cfgstr .= "04_wifi_mode=ap\n";
    } else {
      $cfgstr .= "03_wifi_state=off\n";
      $cfgstr .= "04_wifi_mode=ap\n";
      $cfgstr .= "23_wifi_state_Intfc_II=on\n";
      $cfgstr .= "24_wifi_mode_Intfc_II=join\n";
    }

    $cfgstr .= "25_wifi_ssid_join_Intfc_II=" . $SSID . "\n";
    if (isset($_GET['06'])) {$cfgstr .= "26_wifi_password_join_Intfc_II=" . $_GET['06'] . "\n";}
    $cfgstr = str_replace('*', '', $cfgstr);   
    // Write to default.cfg here

    // write new config
    
    $ssidConfig = "";
    if($ShieldSetting_01 == ""){$ShieldSetting_01 = "admin";}
    $ssidConfig .= "01_user_password=" .  $ShieldSetting_01 . "\n";
    $ssidConfig .= "23_wifi_state_Intfc_II=on\n";
    $ssidConfig .= "24_wifi_mode_Intfc_II=join\n";
    $ssidConfig .= "25_wifi_ssid_join_Intfc_II=" . $SSID . "\n";
    if (isset($_GET['06'])) {$ssidConfig .= "26_wifi_password_join_Intfc_II=" . $_GET['06'] . "\n";}

    write_cfg($ssidConfig);

    append_temp_cfg($cfgstr);
    $command = $q;
    // write_todo($command);
  }

  if($q == "W4"){
    // check_vpnConfig();
    if (isset($_GET['13'])) {$cfgstr .= "13_vpn_nickname=" . 	$_GET['13'] . "\n";}
    $cfgstr .= "14_vpn_email=" .     	$_GET['14'] . "\n";
    $cfgstr = str_replace('*', '', $cfgstr);   
    append_temp_cfg($cfgstr);
    echo $cfgstr;
    $command = $q;
    write_todo($command);
  }

  if($q == "W5"){
    // check_vpnConfig();
    $nick = $_GET['13'];
    $email = $_GET['14'];
    $addy = $_GET['15'];
    echo $addy;
    
    if (isset($_GET['15'])) {$cfgstr .= "15_vpn_wallet_id=" . 	$_GET['15'] . "\n";};
    if (isset($_GET['22'])) {$cfgstr .= "22_nft_index=" . 	$_GET['22'] . "\n";};
    check_vpnConfig($nick,$addy,$email);
    $cfgstr = str_replace('*', '', $cfgstr);   
    append_temp_cfg($cfgstr);
    $command = $q;
    write_todo($command);
  }

  if($q == "W6"){
    // check_vpnConfig();
    if (isset($_GET['16'])) {$cfgstr .= "16_vpn_port=" . 	$_GET['16'] . "\n";}
    $cfgstr .= "10_vpn_enabled=on\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['30'])) {$cfgstr .= "30_PING_ipaddress=" .     $_GET['30'] . "\n";}
    $cfgstr .= "29_ROUTER_enabled=relay\n";
    $cfgstr = str_replace('*', '', $cfgstr);   
    append_temp_cfg($cfgstr);
    copy_and_rename_cfg();
    write_todo('C');
    $command = $q;
    write_todo($command);
  }

  if($q == "W6b"){
    // check_vpnConfig();
    if (isset($_GET['16'])) {$cfgstr .= "16_vpn_port=" . 	$_GET['16'] . "\n";}
    $cfgstr .= "10_vpn_enabled=on\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['30'])) {$cfgstr .= "30_PING_ipaddress=" .     $_GET['30'] . "\n";}
    $cfgstr = str_replace('*', '', $cfgstr);   
    append_temp_cfg($cfgstr);
  }

  if($q == "W6c"){
    // check_vpnConfig();
    if (isset($_GET['07'])) {$cfgstr .= "07_wifi_ssid_AP=" .         $_GET['07'] . "\n";}
    if (isset($_GET['08'])) {$cfgstr .= "08_wifi_password_AP=" .         $_GET['08'] . "\n";}
    $cfgstr .= "03_wifi_state=on\n";
    $cfgstr .= "10_vpn_enabled=on\n";
    $cfgstr .= "29_ROUTER_enabled=hybrid\n";
    $cfgstr = str_replace('*', '', $cfgstr);   
    append_temp_cfg($cfgstr);
    // appendRouterMode();
    copy_and_rename_cfg();
    echo 'Renamed Config';
    write_todo('C');
    write_todo('W6');
  }

  if($q == "W6d"){
    // check_vpnConfig();
    $cfgstr .= "03_wifi_state=on\n";
    $cfgstr .= "04_wifi_mode=ap\n";
    $cfgstr .= "10_vpn_enabled=on\n";
    $cfgstr .= "29_ROUTER_enabled=hybrid\n";
    $cfgstr = str_replace('*', '', $cfgstr);   
    append_temp_cfg($cfgstr);
    // appendRouterMode();
    // write_todo('W6');
  }

  if ($q == "W6e") {
    if (isset($_GET['07'])) {$cfgstr .= "07_wifi_ssid_AP=" .         $_GET['07'] . "\n";}
    if (isset($_GET['08'])) {$cfgstr .= "08_wifi_password_AP=" .         $_GET['08'] . "\n";}
    $cfgstr .= "03_wifi_state=on\n";
    $cfgstr .= "29_ROUTER_enabled=hybrid\n";
    $cfgstr = str_replace('*', '', $cfgstr);   
    append_temp_cfg($cfgstr);
    copy_and_rename_cfg();
    write_todo('C');
    write_todo('W6');
  }


  if($q == "W7") {    // Refesh for wlan1
    $command = $q;
    write_todo($command);
  }

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

  if($q == "WX2") {
      echo json_encode([
        'success' => true,
        'data' => $networksA
    ], JSON_PRETTY_PRINT);
    return;
  }

  if($q == "WX2b") {
    echo json_encode([
      'success' => true,
      'data' => $networksB
  ], JSON_PRETTY_PRINT);
  return;
}

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

  if ($q == "WX0") {
    $settingfile = "./default.cfg";
  // //    if (!(file_exists($settingfile))) { 
  //       if($ShieldSetting_01 == ""){$ShieldSetting_01 = "admin";}
  //       $cfgstr .= "01_user_password=" .  $ShieldSetting_01 . "\n";
  // //    }
    $cfgstr = str_replace('*', '', $cfgstr);
    append_temp_cfg($cfgstr);
  }

  if ($q == "WX1") {
    if (isset($_GET['07'])) {$cfgstr .= "07_wifi_ssid_AP=" .         $_GET['07'] . "\n";}
    if (isset($_GET['08'])) {$cfgstr .= "08_wifi_password_AP=" .         $_GET['08'] . "\n";}
    $cfgstr = str_replace('*', '', $cfgstr);
    append_temp_cfg($cfgstr);
    copy_and_rename_cfg();
    write_todo("W6");
  }


  if ($q == "WX3") {
    $cfgstr .= "03_wifi_state=on\n";
    $cfgstr .= "04_wifi_mode=ap\n";
    $cfgstr .= "29_ROUTER_enabled=router\n";
    $cfgstr .= "10_vpn_enabled=on\n";
    $cfgstr = str_replace('*', '', $cfgstr);
    append_temp_cfg($cfgstr);
    addRouterMode();
    // write_todo("W6");
  }

  if ($q == "WX4") {
    $cfgstr .= "29_ROUTER_enabled=router\n";
    $cfgstr .= "10_vpn_enabled=on\n";
    $cfgstr .= "03_wifi_state=on\n";
    $cfgstr .= "04_wifi_mode=ap\n";
    $cfgstr = str_replace('*', '', $cfgstr);
    append_temp_cfg($cfgstr);
    addRouterMode();
    // write_todo("W6");
  }

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

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

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



  //****************************************************

  if($q == 1){    $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['23'])) {$cfgstr .= "23_wifi_state_Intfc_II=".           $_GET['23'] . "\n";}
    if (isset($_GET['24'])) {$cfgstr .= "24_wifi_mode_Intfc_II=".           $_GET['24'] . "\n";}
    if (isset($_GET['25'])) {$cfgstr .= "25_wifi_ssid_join_Intfc_II=".           $_GET['25'] . "\n";}
    if (isset($_GET['26'])) {$cfgstr .= "26_wifi_password_join_Intfc_II=".           $_GET['26'] . "\n";}
    if (isset($_GET['27'])) {$cfgstr .= "27_wifi_ssid_AP_Intfc_II=".           $_GET['27'] . "\n";}
    if (isset($_GET['28'])) {$cfgstr .= "28_wifi_password_AP_Intfc_II=".           $_GET['28'] . "\n";}
    if (isset($_GET['29'])) {$cfgstr .= "29_ROUTER_enabled=".           $_GET['29'] . "\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_wlan1"] = $SHIELD_wlan1;
  $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_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;

  if($q == 7){     $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;
    // Add the $shieldSettings array to the $reply array under the "Settings" key
    $reply["Settings"] = $shieldSettings;
    $user_setting_status = " "; }
  if($q == 8){    $command = "S";    write_todo($command);  }
  
  // $reply .= "user_setting_status=$user_setting_status$seperator";

  if($q == 6){$reply .= "Hello 6"; }
  
  header('Content-Type: application/json');
  echo json_encode($reply);
  exit;

  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 = "./default.cfg";
    if (file_exists($settingfile)) { 
      unlink($settingfile);
    }
  }

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

  function append_cfg($dothiscfg){
    $settingfile = "./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 write_temp_cfg($dothiscfg){
    // $check = "woah";
    $settingfile = "./temp_default.cfg";
    $myfile = fopen($settingfile, "w") or die("Unable to open file!");
    fwrite($myfile, $dothiscfg);
    // echo $check;
    fclose($myfile);  
  }

  function append_temp_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 copy_and_rename_cfg() {
  //   $default_file = "./default.cfg";
  //   $temp_file = "./temp_default.cfg";

  //   if (file_exists($default_file)) {
  //     // Append contents from default to temp
  //     $contents = file_get_contents($default_file);
  //     file_put_contents($temp_file, $contents, FILE_APPEND);

  //     // Delete original default file
  //     unlink($default_file);

  //     // Rename temp to default
  //   }
  //   rename($temp_file, $default_file);
  // }

  function copy_and_rename_cfg() {
    $default_file = "./default.cfg";
    $temp_file = "./temp_default.cfg";

    if (file_exists($temp_file)) {
        // Read temp file into array
        $temp_lines = file($temp_file, FILE_IGNORE_NEW_LINES);
        
        // Create an associative array to store the latest value for each line number
        $filtered_lines = [];
        $password_lines = []; // Special array for "01" lines
        
        foreach ($temp_lines as $line) {
            if (strlen($line) >= 2) {
                $line_num = substr($line, 0, 2);
                if ($line_num === "01") {
                    // Keep all "01" lines
                    $password_lines[] = $line;
                } elseif (is_numeric($line_num)) {
                    // For all other numeric prefixes, keep only the latest
                    $filtered_lines[$line_num] = $line;
                }
            }
        }
        
        // Combine password lines with other filtered lines and write back to temp file
        $final_content = implode("\n", array_merge($password_lines, array_values($filtered_lines))) . "\n";
        file_put_contents($temp_file, $final_content);
    }

    // Rename temp to default (original behavior)
    if (file_exists($default_file)) {
        unlink($default_file);
    }
    rename($temp_file, $default_file);
}

  function check_vpnConfig($par1, $par2, $par3){
    $apppath = "/home/relayup/";
    $vpnConfigFile = $apppath . 'dev/vpn_config.cfg';

    // Initialize variables
    $bandwidthRate = "";
    $bandwidthBurst = "";
    $myFamily = "";
    $accountingMax = "";
    $accountingStart = "";
    $accountingRule = "";

    // Read existing content if file exists and extract specific values
    if (file_exists($vpnConfigFile)) {
        $existingContent = file_get_contents($vpnConfigFile);
        $lines = explode("\n", $existingContent);
        foreach ($lines as $line) {
            if (strpos($line, "RelayBandwidthRate") === 0) {
                $bandwidthRate = trim($line);
            } elseif (strpos($line, "RelayBandwidthBurst") === 0) {
                $bandwidthBurst = trim($line);
            } elseif (strpos($line, "MyFamily") === 0) {
                $myFamily = trim($line);
            } elseif (strpos($line, "AccountingMax") === 0) {
                $accountingMax = trim($line);
            } elseif (strpos($line, "AccountingStart") === 0) {
                $accountingStart = trim($line);
            } elseif (strpos($line, "AccountingRule") === 0) {
                $accountingRule = trim($line);
            }
        }
    }

    // Build new content in specific order
    $newContent = "";
    if ($accountingMax) {
        $newContent .= $accountingMax . "\n";
    }
    if ($accountingStart) {
        $newContent .= $accountingStart . "\n";
    }
    if ($accountingRule) {
        $newContent .= $accountingRule . "\n";
    }
    if ($bandwidthRate) {
        $newContent .= $bandwidthRate . "\n";
    }
    if ($bandwidthBurst) {
        $newContent .= $bandwidthBurst . "\n";
    }
    
    if ($par1) {
        $newContent .= "Nickname " . $par1 . "\n";
    }
    
    if ($par2 || $par3) {
        $newContent .= "ContactInfo " . trim($par3 . " @anon: " . $par2) . "\n";
    }
    
    $newContent .= "ShutdownWaitLength 10\n" .
                  "MetricsPort 127.0.0.1:8080\n" .
                  "MetricsPortPolicy accept 127.0.0.1\n" .
                  "ControlPort 9051\n";

    if ($myFamily) {
        $newContent .= $myFamily . "\n";
    }

    // Write to file
    file_put_contents($vpnConfigFile, $newContent) or die("Unable to create file: $vpnConfigFile");
  }

  function addRouterMode() {
    if (!isset($apppath)) {
        $apppath = "/home/relayup/";
    }
    
    $vpnConfigFile = $apppath . 'dev/vpn_config.cfg';
    $sourceConfigFile = $apppath . 'dev/routerrc.txt'; 
    
    // Check if source file exists
    if (!file_exists($sourceConfigFile)) {
        return false;  // Or handle error as needed
    }
    
    // Read the content from source file
    $newContent = file_get_contents($sourceConfigFile);
    
    // Replace the content of vpn_config file (this will clear existing content)
    file_put_contents($vpnConfigFile, $newContent);
    
    return true;  // Or return false if any operation fails
}

function appendRouterMode() {
    if (!isset($apppath)) {
        $apppath = "/home/relayup/";
    }
    
    $vpnConfigFile = $apppath . 'dev/vpn_config.cfg';
    $sourceConfigFile = $apppath . 'dev/routerrc.txt';
    
    // Check if source file exists
    if (!file_exists($sourceConfigFile)) {
        return false;
    }
    
    // Read the content from source file
    $newContent = file_get_contents($sourceConfigFile);
    
    // Append the content to vpn_config file
    file_put_contents($vpnConfigFile, $newContent, FILE_APPEND);
    
    return true;
}

?>