// node main.js   9079   x64

import frida from "frida";
// var frida = require("frida");
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));

function onMessage(message, data) {
  if (message.type === 'send') {
      console.log(message.payload);
  } else if (message.type === 'error') {
      console.error(message.stack);
  }
}

function init() {
  let addressSource = '';
  let version = process.argv[2] || "8447";
  let bit = process.argv[3] || "x64";

  try {
    let addressSourceHeadFilePath = path.join(__dirname, `/Core/AddressSource.head`);
    let addressSourceEndFilePath = path.join(__dirname, `/Core/AddressSource.end`);
    
    let addressFilePath = path.join(__dirname, `/Core/WeChatAppEx.exe/address_${version}_${bit}.json`);
    let hookFilePath = path.join(__dirname, `/Core/WeChatAppEx.exe/hook.js`);

    fs.accessSync(addressFilePath);
    addressSource += fs.readFileSync(addressSourceHeadFilePath);
    addressSource += fs.readFileSync(addressFilePath);
    addressSource += fs.readFileSync(addressSourceEndFilePath);
    addressSource += fs.readFileSync(hookFilePath);
  } catch (error) {
    console.log(`暂不支持 ${version}_${bit} 的版本!`, error)
    return '';
  }

  console.log("HOOK文件组装成功!")
  return addressSource;
}

(async () => {
  let addressSource = init();
  if (!addressSource) return;

  var device = await frida.getLocalDevice();
  var processes = await device.enumerateProcesses();
  var pid = -1;
  processes.forEach(async (p_) => {
    if (p_.name == "WeChatAppEx.exe") {
      console.log(p_.name, p_.pid, p_);
      // let commandLine = cmdline.getCmdline(p_.pid);
      // if(commandLine.indexOf("--type=") == -1){
      //     pid = p_.pid;
      // }

      // 第一个就是
      if (pid == -1) {
        pid = p_.pid;
      }
    }
  });
  console.log("WeChatAppEx.exe 主进程 pid = " + pid);
  if (pid == -1) {
    return;
  }

  let session = await frida.attach(pid);
  let script = await session.createScript(addressSource);
  script.message.connect(onMessage);
  await script.load();
})().catch((error) => {
  console.error(error.stack);
});
