1#!/usr/bin/ruby
2# Copyright:: Copyright 2012 Google Inc.
3# License:: All Rights Reserved.
4# Original Author:: Yugui Sonoda (mailto:yugui@google.com)
5#
6# Generates a runnable package of the pepper API example.
7
8require File.join(File.dirname(__FILE__), 'nacl-config')
9require 'json'
10require 'find'
11require 'fileutils'
12
13include NaClConfig
14
15class Installation
16  include NaClConfig
17
18  SRC_DIRS = [ Dir.pwd, HOST_LIB ]
19
20  def initialize(destdir)
21    @destdir = destdir
22    @manifest = {
23      "files" => {}
24    }
25    ruby_libs.each do |path|
26      raise "Collision of #{path}" if @manifest['files'].key? path
27      @manifest['files'][path] = {
28        ARCH => {
29          "url" => path
30        }
31      }
32      if path[/\.so$/]
33        alternate_path = path.gsub('/', "_")
34        raise "Collision of #{alternate_path}" if @manifest['files'].key? alternate_path
35        @manifest['files'][alternate_path] = {
36          ARCH => {
37            "url" => path
38          }
39        }
40      end
41    end
42  end
43
44  def manifest
45    @manifest.dup
46  end
47
48  def install_program(basename)
49    do_install_binary(basename, File.join(@destdir, "bin", ARCH))
50    @manifest["program"] = {
51      ARCH => {
52        "url" => File.join("bin", ARCH, basename)
53      }
54    }
55  end
56
57  def install_library(name, basename)
58    do_install_binary(basename, File.join(@destdir, "lib", ARCH))
59    @manifest["files"][name] = {
60      ARCH => {
61        "url" => File.join("lib", ARCH, basename)
62      }
63    }
64  end
65
66  private
67  def do_install_binary(basename, dest_dir)
68    full_path = nil
69    catch(:found) {
70      SRC_DIRS.each do |path|
71        full_path = File.join(path, basename)
72        if File.exist? full_path
73          throw :found
74        end
75      end
76      raise Errno::ENOENT, "No such file to install: %s" % basename
77    }
78    FileUtils.mkdir_p dest_dir
79    system("#{INSTALL_PROGRAM} #{full_path} #{dest_dir}")
80  end
81
82  def ruby_libs
83    Find.find(RbConfig::CONFIG['rubylibdir']).select{|path| File.file?(path) }.map{|path| path.sub("#{@destdir}/", "") }
84  end
85end
86
87def install(destdir)
88  inst = Installation.new(destdir)
89  manifest = JSON.parse(File.read("pepper-ruby.nmf"))
90
91  program = File.basename(manifest['program'][ARCH]['url'])
92  inst.install_program(program)
93
94  manifest['files'].each do |name, attr|
95    inst.install_library(name, File.basename(attr[ARCH]["url"]))
96  end
97
98  File.open(File.join(destdir, "ruby.nmf"), "w") {|f|
99    f.puts JSON.pretty_generate(inst.manifest)
100  }
101end
102
103def main
104  install(ARGV[0])
105end
106
107if __FILE__ == $0
108  main()
109end
110