~dlh/armagetronad/os-x-toolkit

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
require "fileutils"
require "optparse"
require "pathname"
require "uri"

def all_libraries
  libs = {}

  libs["SDL"] = Builder.new { |config, arch|
    archive = fetch("http://www.libsdl.org/release/SDL-1.2.15.dmg")
    source = open_dmg(archive)
    framework = copy_framework(source, "SDL", arch)
    close_dmg(source)
    apply_patch(path("patches/sdl.diff"), framework)
  }

  libs["SDL_image"] = Builder.new { |config, arch|
    archive = fetch("http://www.libsdl.org/projects/SDL_image/release/SDL_image-1.2.12.dmg")
    source = open_dmg(archive)
    copy_framework(source, "SDL_image", arch)
    close_dmg(source)
  }

  libs["SDL_mixer"] = Builder.new { |config, arch|
    archive = fetch("http://www.libsdl.org/projects/SDL_mixer/release/SDL_mixer-1.2.12.dmg")
    source = open_dmg(archive)
    copy_framework(source, "SDL_mixer", arch)
    close_dmg(source)
  }

  libs["libpng"] = Builder.new("lib/libpng.a") { |config, arch|
    archive = fetch("http://prdownloads.sourceforge.net/libpng/libpng-1.6.14.tar.gz?download")
    source = expand_tgz(archive)
    Dir.chdir(source) do
      config.env_variables(arch)
      system("./configure", "--prefix", install_path(arch), "--disable-shared")
      system("make install")
    end
  }

  libs["freetype"] = Builder.new("lib/libfreetype.a") { |config, arch|
    archive = fetch("http://download.savannah.gnu.org/releases/freetype/freetype-2.5.0.1.tar.gz")
    source = expand_tgz(archive)
    Dir.chdir(source) do
      config.env_variables(arch)
      system("./configure", "--prefix", install_path(arch), "--disable-shared")
      system("make") # In 2.5.0, freetype-config isn't generated when doing just "make install".
      system("make install")
    end
  }

  libs["ftgl"] = Builder.new("lib/libftgl.a") { |config, arch|
    archive = fetch("http://prdownloads.sourceforge.net/ftgl/ftgl-2.1.3-rc5.tar.gz?download")
    source = expand_tgz(archive)
    Dir.chdir(source) do
      config.env_variables(arch)
      system("./configure", "--prefix", install_path(arch), "--disable-shared", "--with-ft-prefix=#{install_path(arch)}", "--disable-freetypetest")
      system("make install")
    end
  }

  libs["protobuf"] = Builder.new("lib/libprotobuf.a") { |config, arch|
    archive = fetch("http://protobuf.googlecode.com/files/protobuf-2.5.0.tar.gz")
    source = expand_tgz(archive)
    Dir.chdir(source) do
      config.env_variables(arch)
      system("./configure", "--prefix", install_path(arch), "--disable-shared")
      system("make install")
    end
  }

  libs["boost"] = Builder.new("lib/libboost_system.a") { |config, arch|
    architecture_option = {
      "i386" => "x86",
      "x86_64" => "x86",
      "ppc" => "ppc"
    }[arch]

    address_model_option = {
      "i386" => "32",
      "x86_64" => "64",
      "ppc" => "32"
    }[arch]

    archive = fetch("http://prdownloads.sourceforge.net/boost/boost_1_54_0.tar.gz?download")
    source = expand_tgz(archive)
    Dir.chdir(source) do
      config.env_variables(arch)
      system("./bootstrap.sh", "--prefix=#{install_path(arch)}")
      system("./b2 -d0 --with-thread architecture=#{architecture_option} address-model=#{address_model_option} link=static cxxflags=#{escape_sh(ENV["CXXFLAGS"])} cflags=#{escape_sh(ENV["CFLAGS"])} linkflags=#{escape_sh(ENV["LDFLAGS"])} install")
    end
  }

  libs["GLEW"] = Builder.new("lib/libGLEW.a") { |config, arch|
    archive = fetch("http://prdownloads.sourceforge.net/glew/glew-1.11.0.tgz?download")
    source = expand_tgz(archive)
    Dir.chdir(source) do
      # GLEW uses their own Makefile-system. It's easier to compile
      # it manually rather than try passing the correct flags to their
      # build system.
      system(
        "gcc",
        "-DGLEW_NO_GLU", "-DGLEW_STATIC",
        "-O2", "-Wall", "-W", "-Iinclude",
        "-dynamic", "-fno-common",
        "-o", "glew.o",
        "-c", "src/glew.c",
        *config.cxxflags(arch)
      )
      system("ar", "cr", "libGLEW.a", "glew.o") # *config.ldflags(arch)

      include_dir = install_path(arch, ["include", "GL"])
      lib_dir = install_path(arch, "lib")
      FileUtils.mkdir_p(lib_dir) if !File.exist?(lib_dir)
      FileUtils.mkdir_p(include_dir) if !File.exist?(include_dir)

      system("install", "-m", "0644", "libGLEW.a", lib_dir)
      system("install", "-m", "0644", "include/GL/glew.h", include_dir)      
    end
  }

  return libs
end

class Builder
  def initialize(lib_file=nil, &build_rules)
    @base_directory = File.expand_path(File.dirname(__FILE__))
    @lib_file = lib_file
    @build_rules = build_rules
  end

  def install(build_config)
    build_config.archs.each do |arch|
      instance_exec(build_config, arch, &@build_rules)
    end
    if @lib_file
      build_config.archs.each do |arch|
        lipo_info(install_path(arch, @lib_file))
      end
    end
  end

  def path(components=[], option=nil)
    p = File.join(@base_directory, *Array(components))
    case option
    when :make_dir
      FileUtils.mkdir_p(p) if !File.exist?(p)
    when :clear_dir
      FileUtils.rm_r(p) if File.exist?(p)
      FileUtils.mkdir_p(p)
    when :clear_file
      FileUtils.rm_r(p) if File.exist?(p)
      base_path = File.dirname(p)
      FileUtils.mkdir_p(base_path) if !File.exist?(base_path)
    end
    return p
  end

  def fetch(url)
    file_name = File.basename(URI.parse(url).path)
    base_path = self.path("work/archives", :make_dir)
    file_path = File.join(base_path, file_name)
    system("curl", "--location", "-o", file_path, url) if !File.exist?(file_path)
    return file_path
  end

  def open_dmg(path)
    file_name = File.basename(path)
    base_path = self.path("work/mounts", :make_dir)
    file_path = File.join(base_path, file_name)
    system("hdiutil", "attach", "-mountpoint", file_path, path)
    return file_path
  end

  def close_dmg(path)
    system("hdiutil", "detach", path)
  end

  def copy_framework(source, name, arch)
    framework_name = "#{name}.framework"
    file_path = self.path("libraries/Frameworks/#{framework_name}", :clear_file)
    FileUtils.cp_r(File.join(source, framework_name), file_path)

    # link lib file
    framework_lib_file = File.join(file_path, name)
    system("lipo", framework_lib_file, "-verify_arch", arch)
    if $?.exitstatus == 0
      symlink_relative(framework_lib_file, self.path("libraries/#{arch}/lib/lib#{name}.dylib", :clear_file))
    else
      puts "Error: '#{framework_name}' is not built for '#{arch}'."
      exit(1)
    end

    # link headers
    header_directory = File.join(file_path, "Headers")
    symlink_relative(header_directory, self.path("libraries/#{arch}/include/#{name}", :clear_file))
    Dir.glob("#{header_directory}/*") do |header_file|
      symlink_relative(header_file, self.path("libraries/#{arch}/include/AllFrameworks/#{File.basename(header_file)}", :clear_file))
    end
    return file_path
  end

  def expand_tgz(path)
    file_path = self.path(["work/sources", File.basename(path)], :clear_dir)
    system("tar", "xzf", path, "-C", file_path, "--strip-components", "1")
    return file_path
  end

  def escape_sh(str)
  	str.to_s.gsub(/(?=[^a-zA-Z0-9_.\/\-\x7F-\xFF\n])/n, '\\').gsub(/\n/, "'\n'").sub(/^$/, "''")
  end

  def lipo_info(path)
    puts "\n========== Running lipo -info #{path}"
    system("lipo", "-info", path)
  end

  def install_path(arch, components=[], option=nil)
    return self.path(["libraries", arch] + Array(components), option)
  end
  
  def symlink_relative(source, target)
    Dir.chdir(File.dirname(target)) do |target_dir|
      source_relative = Pathname.new(source).relative_path_from(Pathname.new(target_dir)).to_s
      FileUtils.ln_s(source_relative, File.basename(target))
    end
  end

  def apply_patch(patch_file, base_directory)
    Dir.chdir(base_directory) do
      IO.popen("patch -p0", "w") do |io|
        io.puts(File.read(patch_file))
        io.close_write
      end
    end
  end
end

class BuildConfiguration
  def initialize(archs, sdk, version_min)
    @archs = archs
    @sdk = sdk
    @version_min = version_min
  end

  attr_reader(:archs)

  def env_variables(arch)
    ENV["CXXFLAGS"] = cxxflags(arch).join(" ")
    ENV["CFLAGS"] = ENV["CXXFLAGS"]
    ENV["LDFLAGS"] = ldflags_full(arch).join(" ")
  end

  def cxxflags(arch)
    flags = ["-arch", arch, "-stdlib=libc++"]
    flags += ["-isysroot", @sdk] if !@sdk.empty?
    flags << "-mmacosx-version-min=#{@version_min}" if !@version_min.empty?
    return flags
  end

  def ldflags(arch)
    flags = []
    flags << "-Wl,-syslibroot,#{@sdk}" if !@sdk.empty?
    return flags
  end

  def ldflags_full(arch)
    flags = ldflags(arch)
    flags += cxxflags(arch)
    return flags
  end
end

def parse_options(libraries)
  options = {
    "libraries_to_install" => [],
    "archs" => [],
    "sdk" => "",
    "version_min" => ""
  }

  parser = OptionParser.new { |opts|
    opts.banner = "Usage: #{$0} [options] [libraries to install...]"

    opts.on("--arch ARCH", "A comma separated list of archs to build") do |value|
      options["archs"] += value.split(",")
    end

    opts.on("--sdk SDK", "A path to the developement SDK") do |value|
      options["sdk"] = value
    end

    opts.on("--version-min VERSION", "The minimum OS X version to build for") do |value|
      options["version_min"] = value
    end

    opts.on("-l", "--list", "List all installable libraries") do
      libraries.keys.sort.each { |name| puts name }
      exit(0)
    end

    opts.on("-a", "--all", "Install all libraries") do
      options["libraries_to_install"] += libraries.keys.sort
    end

    opts.on("-h", "--help", "Print this help message") do
      puts opts
      exit(0)
    end
  }

  begin
    parser.parse!
  rescue OptionParser::ParseError => e
    puts "Error: #{e.message}"
    exit(1)
  end

  options["libraries_to_install"] += ARGV

  if options["libraries_to_install"].empty?
    puts "Error: specify a library to install."
    exit(1)
  end

  if options["archs"].empty?
    puts "Error: specify the arch(s) that will be installed."
    exit(1)
  end

  return options
end

def main
  libraries = all_libraries()
  options = parse_options(libraries)
  build_config = BuildConfiguration.new(options["archs"], options["sdk"], options["version_min"])
  options["libraries_to_install"].each do |library_name|
    lib = libraries[library_name]
    if lib
      lib.install(build_config)
    else
      puts "Error: '#{library_name}' is not an installable library."
    end
  end
end

main() if __FILE__ == $PROGRAM_NAME