#!/usr/bin/env ruby

if $0 == __FILE__
  #ENV['BUNDLE_GEMFILE'] = File.expand_path('../../Gemfile', __FILE__)
  #require "rubygems"
  #require "bundler/setup"
  $:.unshift File.expand_path('../../lib', __FILE__)
end
require 'pathname'
require 'cocoapods/config'


pod_bin = File.expand_path('../pod', __FILE__)
pod_prefix = File.expand_path('../..', pod_bin)

require 'rbconfig'
ruby_bin = File.join(RbConfig::CONFIG['bindir'], RbConfig::CONFIG['ruby_install_name'])
ruby_prefix = RbConfig::CONFIG['prefix']

# TODO how are we going to handle the required tools in the PATH? e.g. git, svn, hg
homebrew_prefix = `brew --prefix`.strip

developer_prefix = `xcode-select --print-path`.strip
xcode_app_path = File.expand_path('../..', developer_prefix)


require 'erb'
profile = ERB.new(DATA.read).result(TOPLEVEL_BINDING)
filename = '/tmp/sandbox-pod.sb'
File.open(filename, 'w') { |f| f.write(profile) }

puts profile

command = ['/usr/bin/sandbox-exec', '-f', filename, pod_bin, *ARGV]
exec *command


__END__
(version 1)
(debug allow)

(allow file-ioctl)
(allow sysctl-read)
(allow file-read-metadata)
(allow mach-lookup)
(allow ipc-posix-shm)
(allow process-fork)
(allow system-socket)

; TODO this doesn’t actually work atm, because appledoc needs to be code signed for apple events to be allowed.
; Needed for appldoc to install a docset
; (allow appleevent-send)

; TODO see if we can restrict this too
;(allow network-outbound (literal "/private/var/run/mDNSResponder"))
(allow network-outbound)

(allow process-exec
  (regex 
    #"^<%= pod_bin %>"
    #"^<%= ruby_bin %>"
    #"^<%= homebrew_prefix %>"
    #"^<%= File.join(developer_prefix, 'usr/bin/xcrun') %>"
    #"^<%= File.join(developer_prefix, 'usr/bin/xcodebuild') %>"
    #"^<%= File.join(developer_prefix, 'usr/bin/docsetutil') %>" ; Needed for appledoc
    #"^/bin/*"
    #"^/usr/bin/*"
  )
)

;; Allow these reads:
(allow file-read*
  (regex
    ; TODO see if we can restrict this more, but it's going to be hard
    #"^/Users/[^.]+/*"
    ;#"^/Users/[^.]+/.netrc"
    ;#"^/Users/[^.]+/.gemrc"
    ;#"^/Users/[^.]+/.gem/*"
    ;#"^/Users/[^.]+/Library/.*"
    #"^/Library/*"
    #"^/System/Library/*"
    #"^/usr/lib/*"
    #"^/usr/share/*"
    #"^/private/*"
    #"^/dev/*"
    #"^<%= homebrew_prefix %>"
    #"^<%= ruby_prefix %>"
    #"^<%= pod_prefix %>"
    #"^<%= xcode_app_path %>"
    #"^<%= Pod::Config.instance.repos_dir %>"
  )
)

;; Allow these writes:
(allow file-write*
  (regex
    #"^<%= Pod::Config.instance.project_root %>"
    #"^/Users/[^.]+/Library/Caches/CocoaPods/*"
    #"^/Users/[^.]+/Library/Developer/Shared/Documentation/DocSets"
    #"^/dev/dtracehelper"
    #"^/dev/tty"
    #"^/dev/null"
    #"^/private/var"
  )
)

(deny default)
