$:.unshift File.expand_path('..', __FILE__)

require "etc"
require "tmpdir"
require "json"

module Flombe
  VERSION = "0.1.0.4"
  
  autoload :Dsl, 'flombe/dsl'
  
  class FlombeError < Exception             ; end
  class MissingXCodeError < FlombeError     ; end
  class BadMacOSXVersionError < FlombeError ; end
  class NoFlombefileError < FlombeError     ; end
  class RunningAsRootError < FlombeError    ; end
  
  class Runner
    RECOMMENDED_LLVM   = 2206

    def self.run
      new.run
    end
    
    def self.warn(msg)
      $stderr.puts "\033[0;31m\033[1m==> \033[0m\033[1m" + msg + "\033[0m"
    end

    def run
      raise BadMacOSXVersionError, "You must have Snow Leopard for Flombe. Sorry bro." unless macosx?
      raise MissingXCodeError, "You must have xcode installed to run Flombe." unless xcode?
      raise NoFlombefileError, "There is no Flombefile here: #{Dir.pwd}" unless flombefile?
      raise RunningAsRootError, "Please do not run this command as root." if root?
      
      if `/usr/bin/xcode-select -print-path` + `/usr/bin/llvm-gcc-4.2 -v 2>&1` =~ /LLVM build (\d{4,})/
        if $1.to_i < RECOMMENDED_LLVM
          warn "You should really upgrade your xcode install for best performance."
        end
      end
      
      run_chef
    end
    
    private
    
    def xcode?
      !`/usr/bin/xcode-select -print-path`.chomp.empty?
    end
    
    def macosx?
      macosx_version >= 10.6
    end
    
    def flombefile?
      File.exist?(flombefile)
    end
    
    def macosx_version
      /(10\.\d+)(\.\d+)?/.match(`/usr/bin/sw_vers -productVersion`.chomp).captures.first.to_f
    end
    
    def root?
      Etc.getpwuid.uid == 0
    end

    def run_chef
      system("chef-solo -j #{dna} -c #{config}")
      exit($?.to_i)
    end

    def sane_xcode_version?
      xcode_path = `/usr/bin/xcode-select -print-path`.chomp
      if xcode_path.empty?
        false
      elsif `#{xcode_path}/usr/bin/llvm-gcc-4.2 -v 2>&1` =~ /LLVM build (\d{4,})/
        if $1.to_i < RECOMMENDED_LLVM
          warn "You should really upgrade your xcode install"
        end
        true
      end
    end

    def flombefile
      @flombefile ||= File.expand_path(File.join(Dir.pwd, "Flombefile"))
    end
    
    def flombe_definition
      @flombe ||= Flombe::Dsl.evaluate(flombefile)
    end

    def config
      config_file = File.expand_path(File.join(Dir.tmpdir, "solo.rb"))
      File.open(config_file, "w") do |fp|
        fp.write( flombe_definition.to_solo_config )
      end
      config_file
    end
    
    def dna
      dna_file = File.expand_path(File.join(Dir.tmpdir, "dna.json"))
      File.open(dna_file, "w") do |fp|
        fp.write( flombe_definition.to_dna )
      end
      dna_file
    end
  end
end