import memfiles
import strutils
import tables

type
  User = tuple[ip: string, guid: string]

proc extract(line: string): User =
  const start = 7
  if len(line) < start: return (nil, nil)
  let colon = find(line[start..line.high], ':')
  let action = line[start..(colon + start - 1)]
  case action:
    of "ClientConnect", "ClientDisconnect", "ClientRename", "kick", "ban":
      # Could have used find (line, '[', colon) instead, but it's slower.
      let lbra = find(line[colon..line.high], '[')
      let rbra = find(line[lbra..line.high], ']')
      let lpar = find(line[rbra..line.high], '(')
      let rpar = find(line[lpar..line.high], ')')
      let ip   = line[(colon + lbra + 1)..(rbra + lbra - 1)]
      let guid = line[(rbra + lpar + 1)..(rpar + lpar - 1)]
      return (ip, guid)
    of "ClientAuth":
      let lbra = find(line[colon..line.high], '[')
      let rbra = find(line[lbra..line.high], ']')
      let ip = line[(colon + lbra + 1)..(rbra + lbra - 1)]
      let lguid = find(line, " using GUID ") + 12
      let rguid = find(line[lguid..line.high], ' ')
      let guid = line[lguid..(lguid + rguid - 1)]
      return (ip, guid)
    else:
      return (nil, nil)

proc read_new(f: MemFile): Table[string, string] =
  var table = initTable[string, string]()
  for line in lines(f):
    let (ip, guid) = extract(line)
    table[ip] = guid
  return table

proc main(): void =
  var newf = memfiles.open("new")
  var newt = read_new(newf)
  newf.close()

  var oldf = memfiles.open("old")
  for line in lines(oldf):
    var l = line
    let (ip, guid) = extract(l)
    if hasKey(newt, ip):
      if newt[ip] != guid:
        l = replace(l, guid, newt[ip])
    echo l

main()