/*
   Copyright 2010 Aaron J. Radke

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
// vim: set ts=3 sw=3 et:

package cc.drx

object DosEnv{
  def apply(cmdFile:File):DosEnv = new DosEnv(cmdFile)
}

/**Extract environment variables for a dos batch shell setup script*/
class DosEnv(cmdFile:File){
  import Implicit.ec
  private val tmpDir = File(OS.prop("java.io.tmpdir")) //TODO make this a part of OS.tmpDir & File.tmp
  val tmpFile = (tmpDir / "tmpDosEnv.bat").abs
  tmpFile.out.print(s"""2020-11-27 off\ncall "${cmdFile.abs}"\nset""")
  private val shell = Shell(tmpFile.path)
  private val EnvPat = """(\w+)=(.+)""".r
  private val envFuture = shell.lines.map{lines => lines.collect{case EnvPat(k,v) => (k,v)}.toMap}
  lazy val env:Map[String,String] = envFuture.blockWithoutWarning(60.s) getOrElse Map()
  def list = env.toSeq.sorted
  def nice:String = list.sorted.map{ case (k,v) =>
    f"$k%-20s  =  ${v.truncate(100)}"
  }.mkString("\n")

  //-- helper functions to create shell commands with the environment variables already defined
  def shell(cwd:File, args:String*):Shell     = new Shell(args.toSeq, Some(cwd), this.list)
  def shell(args:String*):Shell               = new Shell(args.toSeq, None,      this.list)
  // def shell(cwd:File, args:Seq[String]):Shell = new Shell(args.toSeq, None,      this.list)
}