// ===== anthos-up:常驻节点服务(daemon) =====
// 职责:残清→ensure_epmd→起 erl(--node 名/--cookie)→就绪窗自探→写发现
// 文件(名+pid+cookie=缺省 session)→loop(超时检查+erl 探活)→退出杀+清文件。
// 纪律:我方探连名固定 up0(随机名秒杀坑);探活走 ps 探测不占 dist 连接
// (tick 泵义务零);erl 驻留 3600000(sleep(infinity) 曾引 discard,已证形)。
// moonrun 面:Cmd::output() 挂——shell 回传一律 run()+文件回传形。

///|
/// CLI 版本位(与 moon.mod version 同步改——发布两处纪律)
const VERSION : String = "0.2.2"

///|
/// 发现文件(缺省 session:名+pid+cookie)
const DISCOVER_FILE : String = "/tmp/anthos_up.node"

///|
/// shell 回传文件序号(stale 面清零:每调用唯一文件)
let ret_seq : Array[Int32] = [0]

///|
/// shell 回传(run()+唯一文件——output() 挂/共享文件 stale 两坑)
async fn sh_ret(cmd : String) -> String {
  ret_seq[0] += 1
  let f = "/tmp/anthos_up_ret_\{ret_seq[0]}.txt"
  // 外括形:重定向绑整串(a||b; c > f 的优先级咬——家法三犯治本)
  let _ = @shell.Cmd("sh", ["-c", "( \{cmd} ) > \{f} 2>/dev/null"]).run() catch {
    _ => ()
  }
  // 读重试窗:run 归后文件写穿透是 host 异步(空串=重试,读到即新)
  for i in 0..<20 {
    let data = @fs.read_file(f) catch {
      _ => {
        @async.sleep(50)
        continue
      }
    }
    let t = @utf8.decode_lossy(data.binary()).trim().to_owned()
    if t.length() > 0 {
      let _ = @shell.Cmd("sh", ["-c", "rm -f \{f}"]).run() catch { _ => () }
      return t
    }
    @async.sleep(50)
  }
  ""
}

///|
/// erl 路径(PATH 优先,kerl 回退)
async fn erl_path() -> String {
  let p = sh_ret("command -v erl || echo /home/thy/kerl/erlang/bin/erl")
  if p.length() > 0 {
    p
  } else {
    "/home/thy/kerl/erlang/bin/erl"
  }
}

///|
/// epmd 保障(PATH+kerl 两试,幂等 ignore)
async fn ensure_epmd() -> Unit {
  let _ = @shell.Cmd("sh", [
    "-c", "epmd -daemon 2>/dev/null || /home/thy/kerl/erlang/bin/epmd -daemon 2>/dev/null || true",
  ]).run() catch {
    _ => ()
  }
}

///|
/// 残清(ps|grep|awk 管道——括号技防 grep 自咬;pkill 禁)
async fn clean_stale() -> Unit {
  let _ = @shell.Cmd("sh", [
    "-c", "ps ax | grep 'sname anthos_u[p]' | awk '{print $1}' | xargs -r kill -9",
  ]).run() catch {
    _ => ()
  }
}

///|
/// 就绪窗自探(epmd 表探——connect 对不存在节点有假 Ok 面,弃)
async fn wait_ready(node_short : String) -> Bool {
  for i in 0..<30 {
    let n = sh_ret(
      "epmd -names 2>/dev/null || /home/thy/kerl/erlang/bin/epmd -names; true",
    )
    if n.contains("name \{node_short} ") || n.contains("name \{node_short}\n") {
      return true
    }
    @async.sleep(800)
  }
  false
}

///|
/// 写发现文件(名+pid+cookie——eval 缺省 session)
async fn write_discover(node : String, pid : Int32, cookie : String) -> Unit {
  let text = "node=\{node}\npid=\{pid}\ncookie=\{cookie}\n"
  @fs.write_file(DISCOVER_FILE, text) catch {
    _ => ()
  }
}

///|
/// 清发现文件
async fn clear_discover() -> Unit {
  let _ = @shell.Cmd("sh", ["-c", "rm -f \{DISCOVER_FILE}"]).run() catch {
    _ => ()
  }
}

///|
/// ms 串→Int64(非数字/溢=inf 哨兵 -1)
fn parse_ms(v : String) -> Int64 {
  let cs = v.to_array()
  if cs.length() == 0 {
    return -1L
  }
  let mut acc = 0L
  for i in 0.. 57 {
      return -1L
    }
    acc = acc * 10L + (c - 48).to_int64()
    if acc > 31536000000L {
      return -1L
    }
  }
  acc
}

///|
async fn main {
  // 参数面:--node(默认 anthos_up)/--cookie(默认 moonbit123)/--timeout(ms|inf)
  let args = @env.args()
  for ai in 0../dev/null 2>&1 || [ -x \{erl} ] ; echo $?",
  )
  if found != "0" {
    eprintln(
      "error: erl 未找到(尝试路径: \{erl})——请安装 Erlang/OTP",
    )
    return
  }
  // 残清+epmd
  clean_stale()
  ensure_epmd()
  // 起 erl
  // nohup+& 起形(moonrun 直 spawn 的 erl 速死=SIGHUP 族;探针三形对照
  // 定谳:sh -c 'nohup erl ... &' 活)+$! 回写真 pid
  let _sh = @process.spawn_orphan("sh", [
    "-c",
    "nohup \{erl} -sname \{node_short} -setcookie \{cookie} -noshell -eval 'timer:sleep(3600000).' >/tmp/anthos_up_erl.log 2>&1 & echo $! > /tmp/anthos_up.pid",
  ]) catch {
    _ => {
      eprintln("error: erl 启动失败: \{erl}")
      return
    }
  }
  @async.sleep(300)
  let pid_text = sh_ret("cat /tmp/anthos_up.pid")
  let pid = parse_pid(pid_text)
  if pid <= 0 {
    eprintln(
      "error: pid 读取失败(\{pid_text})——日志 /tmp/anthos_up_erl.log",
    )
    return
  }
  // 就绪窗自探
  let ready = wait_ready(node_short)
  if !ready {
    eprintln(
      "error: 节点 \{node_short} 就绪超时(erl pid=\{pid},日志 /tmp/anthos_up_erl.log)",
    )
    let _ = @shell.Cmd("kill", ["-9", "\{pid}"]).run() catch { _ => () }
    return
  }
  // 发现文件+就绪报告
  write_discover(node_short, pid, cookie)
  eprintln(
    "节点 \{node_short} 就绪(pid=\{pid})——发现文件 /tmp/anthos_up.node",
  )
  eprintln("  moonx thy1016/anthos-eval \"40 + 2\"(eval 缺省读发现文件)")
  eprintln("  export ANTHOS_NODE=\{node_short}(可选)")
  // loop:超时检查+erl 探活(1s tick;ps 探不占 dist 连接)
  let start = @async.now()
  let mut alive = true
  while alive {
    @async.sleep(1000)
    let state = sh_ret("ps -p \{pid} >/dev/null 2>&1 && echo A || echo D")
    if state != "A" {
      eprintln("erl 已退出(pid=\{pid})")
      alive = false
    } else if timeout_ms > 0L {
      let elapsed = @async.now() - start
      if elapsed >= timeout_ms {
        eprintln("超时(\{timeout_ms}ms)——正在停止节点")
        alive = false
      }
    }
  }
  // 收割:杀 erl+清文件
  let _ = @shell.Cmd("kill", ["-9", "\{pid}"]).run() catch { _ => () }
  clear_discover()
  eprintln("已停止(节点已终止,发现文件已清理)")
}

///|
/// pid 串→Int32(空/非数字=0)
fn parse_pid(v : String) -> Int32 {
  parse_pid_i(v)
}

///|
fn parse_pid_i(v : String) -> Int32 {
  let cs = v.to_array()
  if cs.length() == 0 {
    return 0
  }
  let mut acc : Int32 = 0
  for i in 0.. 57 {
      return 0
    }
    acc = acc * 10 + (c - 48)
  }
  acc
}

///|
/// 用法
fn print_usage() -> Unit {
  println("anthos-up \{VERSION} — moonanthos 常驻节点服务")
  println("用法: anthos-up [选项]")
  println("选项:")
  println("  --node <名>         节点短名(默认 anthos_up)")
  println("  --cookie <串>       dist cookie(默认 moonbit123)")
  println("  --timeout   超时后停止节点(默认 inf)")
  println("  --version, -V       显示版本")
  println("  --help, -h          显示帮助")
}