#!/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_root = File.expand_path('../..', pod_bin)

ruby_bin = `rbenv which ruby`.strip
ruby_root = File.expand_path('../..', ruby_bin)


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 process-exec
  (regex 
    #"^<%= pod_bin %>"
    #"^<%= ruby_bin %>"
    #"^/usr/bin/*"
  )
)

;; Allow these reads:
(allow file-read*
  (regex
    #"^/Users/[^.]+/.gemrc"
    #"^/Users/[^.]+/.gem/*"
    #"^/Library/*"
    #"^/System/Library/*"
    #"^/usr/lib/*"
    #"^/usr/share/*"
    #"^/private/*"
    #"^/dev/*"
    #"^<%= File.join(ruby_root, '*') %>"
    #"^<%= File.join(pod_root, '*') %>"
    #"^<%= Pod::Config.instance.repos_dir %>"
  )
)

;; Allow these writes:
(allow file-write*
  (regex
    #"^<%= File.join(Pod::Config.instance.project_root, '*') %>"
    ;#"^/Users/[^.]+/Library/.*"
    ;#"^/private/var/*"
    #"^/dev/dtracehelper"
  )
)

(deny default)
