#
#
#             Nimrod Bootstrap Program
#        (c) Copyright 2009 Andreas Rumpf
#
#    See the file "copying.txt", included in this
#    distribution, for details about the copyright.
#

import
  os, strutils

const
  BootCmd = [
    "nimrod cc --compile:build/platdef.c $1 rod/nimrod.nim",
    "bin/nimrod cc --compile:build/platdef.c $1 rod/nimrod.nim"
  ]
  PlatdefCTmpl = """
/* Generated by boot.nim */
char* nimOS(void) { return "$1"; }
char* nimCPU(void) { return "$2"; }
"""

proc exec(cmd: string) =
  echo(cmd)
  if executeShellCommand(cmd) != 0: quit("FAILURE")

proc writePlatdefC =
  var f: TFile
  if openFile(f, "build/platdef.c", fmWrite): 
    write(f, PlatdefcTmpl % [system.hostOS, system.hostCPU])
    closeFile(f)
  else:
    quit("Cannot write 'build/platdef.c'\n")
  
proc rodsrc = 
  const
    blacklist = ["nsystem", "nmath", "nos", "osproc", "ntime", "strutils"]
    cmd = "nimrod boot --skip_proj_cfg -o:rod/$1.nim nim/$1"
  for fi in walkFiles("nim/*.pas"):
    var f = extractFileTrunk(fi)
    if find(blacklist, f) >= 0: continue
    var r = "rod" / appendFileExt(f, "nim")
    if not existsFile(r) or fileNewer(fi, r):
      Exec(cmd % f)
  
proc boot(args: string) =
  writePlatdefC()
  rodsrc()
  var newExe = appendFileExt("rod/nimrod", ExeExt)
  var oldExe = appendFileExt("bin/nimrod", ExeExt)
  for i in 0..1:
    Echo("iteration: ", $(i+1))
    # use the new executable to compile the files in the bootstrap directory:
    Exec(Bootcmd[i] % args)
    if sameFileContent(newExe, oldExe): 
      Echo("executables are equal: SUCCESS!")
      return
    else:
      Echo("executables are not equal: compile once again...")
      # move the new executable to bin directory:
      os.moveFile(oldExe, newExe)
  Echo("[Warning] executables are still not equal")

var a = ""
for i in 1 .. paramCount():
  add(a, ' ')
  add(a, paramStr(i))
boot(a)