var DEBUG = false;
var isMobile = false;
var USE_ORIGIN = "";
const SwalConfig = {
  color: "#79F257",
  background: "#022601",
  buttonsStyling: false,
  showClass: {
    backdrop: 'swal2-noanimation',
    popup: '',
    icon: ''
  },
  hideClass: {
    popup: '',
  }
};
const invalidChars = ["/", "\\", ">", "<", ":", "*", "|", '"', "'", "?", "\0"];
const failMsg = (msg) => {
  Swal.fire({
    ...SwalConfig,
    title: "Error!",
    text: msg,
  });
};
const replaceInvalid = (str) => {
  var cache = str;
  invalidChars.forEach((ch) => {
    cache = cache.replaceAll(ch, "#");
  });
  return cache;
};
const post = (url, data, callback) => {
  var settings = {
    url: url,
    method: "POST",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded"
    },
    data: data
  };
  $.ajax(settings).done((data) => {
    if (typeof data.token !== "undefined") {
      localStorage.setItem("tty_token", data.token);
    }
    callback(data);
  });
};
const saveFile = (name, type, data) => {
  if (data !== null && navigator.msSaveBlob)
    return navigator.msSaveBlob(new Blob([data], { type: type }), name);
  var a = $("");
  var url = window.URL.createObjectURL(new Blob([data], { type: type }));
  a.attr("href", url);
  a.attr("download", name);
  $("body").append(a);
  a[0].click();
  window.URL.revokeObjectURL(url);
  a.remove();
};
const validatePubKey = (key) => {
  return /^(ssh-rsa AAAAB3NzaC1yc2|ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNT|ecdsa-sha2-nistp384 AAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzOD|ecdsa-sha2-nistp521 AAAAE2VjZHNhLXNoYTItbmlzdHA1MjEAAAAIbmlzdHA1Mj|ssh-ed25519 AAAAC3NzaC1lZDI1NTE5|ssh-dss AAAAB3NzaC1kc3)[0-9A-Za-z+\/]+[=]{0,3}( .*)?$/.test(
    key
  );
};
const sendSSH = (key, id, token) => {
  var payload = {
    pubkey: key,
    token: token,
  };
  post(USE_ORIGIN + "/auth/setKey.php", payload, (response) => {
    if (!response.error) {
      localStorage.setItem("tty_token", response.refreshToken);
      Swal.fire({
        ...SwalConfig,
        title: "Success!",
        text: "Your key has been uploaded to the server.",
      });
    } else {
      Swal.fire({
        ...SwalConfig,
        title: "Failed!",
        text: response.error,
      }).then(() => {
        window.location.reload();
      });
    }
  });
};
const generateSSH = async () => {
  if (window.location.protocol === "http:") {
    Swal.fire({
      ...SwalConfig,
      title: "Error!",
      text: "You must use HTTPS to generate keys.",
    });
    return;
  }
  var token = localStorage.getItem("tty_token");
  var userData = localStorage.getItem("tty_userData");
  if (!token || !userData || token == "undefined" || userData == "undefined") {
    failMsg("Not Logged In");
    return;
  }
  userData = JSON.parse(userData);
  generateKeyPair("RSASSA-PKCS1-v1_5", 4096, "WebGen " + Date())
    .then((keys) => {
      var KeyExport = new JSZip();
      var name = replaceInvalid(userData.username);
      KeyExport.file("HackersTownTTY-" + name, keys[0]);
      KeyExport.file("HackersTownTTY-" + name + ".pub", keys[1]);
      KeyExport.generateAsync({ type: "blob" }).then((content) => {
        saveFile("HackersTownTTY-" + name + ".zip", "application/zip", content);
      });
      sendSSH(keys[1], userData.id, token);
    })
    .catch((err) => {
      console.log(err);
      failMsg("Failed to generate keypair locally.");
    });
};
const testSwal = () => {
  Swal.fire({
    ...SwalConfig,
    title: "Success!",
  });
};
const uploadSSH = () => {
  var token = localStorage.getItem("tty_token");
  var userData = localStorage.getItem("tty_userData");
  if (!token || !userData || token == "undefined" || userData == "undefined") {
    failMsg("Not Logged In");
    return;
  }
  userData = JSON.parse(userData);
  //request local file
  var kf = document.getElementById("keyfile");
  kf.onchange = function (e) {
    // File selected
    var file = e.target.files[0];
    if (file) {
      var reader = new FileReader();
      reader.readAsText(file, "UTF-8");
      reader.onload = function (evt) {
        var pubkey = evt.target.result;
        pubkey = pubkey.replace(/\r\n/g, "\n");
        pubkey = pubkey.replace(/\n/g, "");
        if (validatePubKey(pubkey)) {
          sendSSH(pubkey, userData.id, token);
        } else {
          failMsg("Invalid key");
        }
      };
      reader.onerror = function (evt) {
        failMsg("Unable to load Keyfile");
      };
    }
  };
  kf.click();
};
const displayFingerprints = () => {
  // Get SSH Fingerprints and display them
  $.get(USE_ORIGIN + "/fingerprint.php", (response) => {
    if (response) {
      var html =
        '
| Bits | Fingerprint (SHA256) | Algorithm | 
|---|
';
      response.split("\n").forEach((line) => {
        var parts = line.split(" ");
        if (parts.length === 4) {
          html +=
            '| ' +
            parts[0] +
            ' | ' +
            parts[1].replace("SHA256:", "") +
            ' | ' +
            parts[3].replace("(", "").replace(")", "") +
            " | 
";
        }
      });
      html += "