/**
 * CHANGES (by Joost Visser)
 * 
 * Strategy pack-modules(pack, dep-base) now takes two additonal 
 *   options:
 *     -dep target
 *     -nodep
 *
 *   The first one specifies the maketarget and basename of the
 *   dependency file that is created. If this option is not passed,
 *   the argument dep-base is used instead. Finally, the -nodep option
 *   can be used to disable this and prevent any dependency file to
 *   be created. Note that -dep takes precendence over -nodep.
 *
 * An additional strategy pack-modules(pack) was added that behaves
 * like pack-modules, except no default for the dependency file 
 * base name needs to be specified. Hence, only the command line
 * options are relevant.
 * 
 * by Eelco Visser (2002-12-18): 
 * Refactored using new (config-style) option handling.
 */
module strategy/pack/modules
imports 
  util/config/options 
  strategy/pack/graph 
  lang/dynamic-rules
  util/config/common
  util/config/verbose

strategies

  pack-options =
    ArgOption("-I" + "--Include",        
	where(<extend-config>("-I", ["-I", <id>])); !(),
	!"-I d | --Include d   Include modules from directory d")

  + Option("--nodep" + "-nodep", 
	where(<set-config> ("-nodep", "")); !(),
	!"--nodep              Don't create dependency file")

  + ArgOption("--dep" + "-d" + "-dep",
	where(<set-config> ("-dep", <id>)); !(),
	!"--dep f | -d f       Write dependency to file f")

  pack-modules(pack : (term -> term) * term -> term)
    = pack-modules(pack, fail)
      <+ <fatal-error> ["Packing modules failed"]

  pack-modules(pack : (term -> term) * term -> term, dep-base) =
    option-wrap(pack-options <+ io-options,
      (<get-config; filter(not("-I"))> "-I" <+ ![]) => path
      ; (<get-config> "-i" <+ !stdin()) => infile
      ; (<get-config> "-o" <+ !stdout()) => outfile
      ; <pack(!path)> infile => (files, spec)
      ; (<get-config> "-b"; <WriteToBinaryFile>(outfile, spec)
         <+ <WriteToTextFile>(outfile, spec))
      ; try((<get-config> "-dep" <+ not(<get-config> "-nodep"); dep-base) => depfile
            ; <create-dep-file(!depfile)> (outfile, files))
    )

  create-dep-file(dep-base) :
    (outfile, files) -> (outfile, files)
    where <dep-base> outfile => out  
	; <fopen> (<add-extension> (out, "dep"), "w") => dep
	; <fprintnl> (dep, [out | <separate-by(!" \\\n\t")> [" :" | files]])
	; <fclose> dep