
var systemCtrl = require("systemCtrl.js");
// WPA
function retStrByWpa(ssid, psw, bssid) {
  const bssidLine = bssid ? `    bssid=${bssid}\n` : '';
  return `ctrl_interface=/tmp/wpa_supplicant/sockets\nupdate_config=1\nnetwork={\n    ssid="${ssid}"\n    psk="${psw}"\n${bssidLine}}`;
}

// WEP
function retStrByWep(ssid, psw, bssid) {
  const bssidLine = bssid ? `    bssid=${bssid}\n` : '';
  return `ctrl_interface=/tmp/wpa_supplicant/sockets\nupdate_config=1\npmf=1\nnetwork={\n    ssid="${ssid}"\n    key_mgmt=NONE\n    auth_alg=OPEN SHARED\n    wep_key0=${psw}\n${bssidLine}}`;
}

// Open
function retStrByOpen(ssid, psw, bssid) {
  const bssidLine = bssid ? `    bssid=${bssid}\n` : '';
  return `ctrl_interface=/tmp/wpa_supplicant/sockets\nupdate_config=1\npmf=1\nnetwork={\n    ssid="${ssid}"\n    key_mgmt=NONE\n${bssidLine}}`;
}

function set(ssid, psw, mode, bssid) {
  // 参数兜底
  if (typeof ssid !== 'string' || !ssid) ssid = '12345678';
  if (typeof psw  !== 'string' || !psw)  psw  = '12345678';

  let rule = '';
  switch (mode) {
    case 'WPA':
    case 'WPA2':
    case 'WPA3':
      rule = retStrByWpa(ssid, psw, bssid);
      break;
    case 'WEP':
      rule = retStrByWep(ssid, psw, bssid);
      break;
    case 'Open':
      rule = retStrByOpen(ssid, psw, bssid);
      break;
    default:
      rule = retStrByWpa(ssid, psw, bssid);
  }

  const shellCmd = `echo -e '${rule}' > /tmp/wpa_supplicant.conf`;
  systemCtrl.executeSystemCommand(shellCmd);
  systemCtrl.executePrint(shellCmd);
}

module.exports = {
  set: set,
};
