module Babushka
  module RunHelpers
    include LogHelpers
    include ShellHelpers
    include PathHelpers

    def _by_babushka
      "by babushka-#{VERSION} at #{Time.now}"
    end

    def edited_by_babushka
      "This line edited #{_by_babushka}"
    end

    def added_by_babushka nlines
      if nlines == 1
        "This line added #{_by_babushka}"
      else
        "These #{nlines} lines added #{_by_babushka}"
      end
    end

    def babushka_config? path
      if !path.p.exists?
        unmet "the config hasn't been generated yet"
      elsif !grep(/Generated by babushka/, path)
        unmet "the config needs to be regenerated"
      else
        true
      end
    end

    def render_erb erb, opts = {}
      if (path = erb_path_for(erb)).nil?
        log_error "If you use #render_erb within a dynamically defined dep, you have to give the full path to the erb template."
      elsif !File.exists?(path)
        log_error "Couldn't find erb to render at #{path}."
      elsif File.exists?(path)
        Renderable.new(opts[:to]).render(path, opts.merge(:context => self)).tap {|result|
          if result
            log "Rendered #{opts[:to]}."
          else
            log_error "Couldn't render #{opts[:to]}."
          end
        }
      end
    end

    def erb_path_for erb
      if erb.to_s.starts_with? '/'
        erb # absolute path
      elsif load_path
        File.dirname(load_path) / erb # directory this dep is in, plus relative path
      end
    end
  end
end
