# For Bundler.with_clean_env
require 'bundler/setup'

PACKAGE_NAME = "traveling-fastlane"
VERSION = "1.15.3"
TRAVELING_RUBY_VERSION = "20150715-2.2.2"
JSON_VERSION = '1.8.2'
UNF_VERSION = '0.0.6'
CA_CERT_URL = 'https://curl.haxx.se/ca/cacert.pem' # from cURL

# Be sure to add the name of a script here when you add it to actions
SCRIPTS = [
  'app_produce',
  'authenticate',
  'ensure_app_exists',
  'funcs',
  'list_devices',
  'manage_ad_hoc_provisioning_profile',
  'manage_dist_certs',
  'manage_provisioning_profiles',
  'manage_push_keys',
  'new_manage_provisioning_profiles',
  'pilot_upload',
  'preload',
  'resolve_itc_team_id',
  'supply_android',
]

desc "Package your app"
task :package => ['clean', 'package:linux:x86_64', 'package:osx']

task :clean do
  sh "rm -rf #{PACKAGE_NAME}-*-osx #{PACKAGE_NAME}-*-linux-x86_64 *.gz"
  sh "rm -rf publishing/darwin/dist"
  sh "rm -rf publishing/linux/dist"
end

namespace :package do

  namespace :linux do
    desc "Package your app for Linux x86_64"
    task :x86_64 => [:bundle_install,
                     "packaging/traveling-ruby-#{TRAVELING_RUBY_VERSION}-linux-x86_64.tar.gz",
                     "packaging/traveling-ruby-#{TRAVELING_RUBY_VERSION}-linux-x86_64-json-#{JSON_VERSION}.tar.gz",
                     "packaging/traveling-ruby-#{TRAVELING_RUBY_VERSION}-linux-x86_64-unf_ext-#{UNF_VERSION}.tar.gz"] do
      create_package("linux-x86_64")
    end
  end


  desc "Package your app for OS X"
  task :osx => [:bundle_install,
                "packaging/traveling-ruby-#{TRAVELING_RUBY_VERSION}-osx.tar.gz",
                "packaging/traveling-ruby-#{TRAVELING_RUBY_VERSION}-osx-json-#{JSON_VERSION}.tar.gz",
                "packaging/traveling-ruby-#{TRAVELING_RUBY_VERSION}-osx-unf_ext-#{UNF_VERSION}.tar.gz"] do
    create_package("osx")
  end

  desc "Install gems to local directory"
  # Remember that need to use the same toolchain as what traveling ruby uses
  task :bundle_install do
    if RUBY_VERSION !~ /^2\.2\./
      abort "You can only 'bundle install' using Ruby 2.2, because that's what Traveling Ruby uses."
    end
    sh "rm -rf packaging/tmp"
    sh "mkdir packaging/tmp"
    sh "cp Gemfile Gemfile.lock packaging/tmp/"
    Bundler.with_clean_env do
      sh "cd packaging/tmp && env BUNDLE_IGNORE_CONFIG=1 bundle install --deployment --path ../vendor --without development"
    end
    sh "rm -rf packaging/tmp"
    sh "rm -f packaging/vendor/*/*/cache/*"
    sh "rm -rf packaging/vendor/ruby/*/extensions"

    sh "find packaging/vendor/ruby/*/gems -name '*.so' | xargs rm -f"
    sh "find packaging/vendor/ruby/*/gems -name '*.bundle' | xargs rm -f"
    sh "find packaging/vendor/ruby/*/gems -name '*.o' | xargs rm -f"
  end
end

# The Ruby interpreter and runtime itself
file "packaging/traveling-ruby-#{TRAVELING_RUBY_VERSION}-linux-x86_64.tar.gz" do
  download_runtime("linux-x86_64")
end

file "packaging/traveling-ruby-#{TRAVELING_RUBY_VERSION}-osx.tar.gz" do
  download_runtime("osx")
end


# The two native dependencies Gems, two per platform.

# json
file "packaging/traveling-ruby-#{TRAVELING_RUBY_VERSION}-linux-x86_64-json-#{JSON_VERSION}.tar.gz" do
  download_native_extension("linux-x86_64", "json-#{JSON_VERSION}")
end

file "packaging/traveling-ruby-#{TRAVELING_RUBY_VERSION}-osx-json-#{JSON_VERSION}.tar.gz" do
  download_native_extension("osx", "json-#{JSON_VERSION}")
end


# unf_ext
file "packaging/traveling-ruby-#{TRAVELING_RUBY_VERSION}-linux-x86_64-unf_ext-#{UNF_VERSION}.tar.gz" do
  download_native_extension("linux-x86_64", "unf_ext-#{UNF_VERSION}")
end

file "packaging/traveling-ruby-#{TRAVELING_RUBY_VERSION}-osx-unf_ext-#{UNF_VERSION}.tar.gz" do
  download_native_extension("osx", "unf_ext-#{UNF_VERSION}")
end

def create_package target
  package_dir = "#{PACKAGE_NAME}-#{VERSION}-#{target}"
  sh "rm -rf #{package_dir}"
  sh "mkdir #{package_dir}"
  sh "mkdir -p #{package_dir}/lib/app"
  for script in SCRIPTS do
    sh "cp actions/#{script}.rb #{package_dir}/lib/app/"
  end
  sh "mkdir #{package_dir}/lib/ruby"
  sh "tar -xzf packaging/traveling-ruby-#{TRAVELING_RUBY_VERSION}-#{target}.tar.gz -C #{package_dir}/lib/ruby"

  # Hack to replace traveling ruby's expired ca-bundle.crt with cURL's most recent one
  # TODO: Remove this when https://github.com/phusion/traveling-ruby/pull/102 lands upstream and we upgrade from traveling ruby version 20150715-2.2.2
  sh "curl -o #{package_dir}/lib/ruby/lib/ca-bundle.crt #{CA_CERT_URL}"

  for script in SCRIPTS do
    if script != 'funcs' && script != 'preload'
      sh "cp wrappers/#{script}_wrapper.sh #{package_dir}/#{script}"
    end
  end
  sh "cp -pR packaging/vendor #{package_dir}/lib/"
  sh "cp Gemfile Gemfile.lock #{package_dir}/lib/vendor/"
  sh "mkdir #{package_dir}/lib/vendor/.bundle"
  sh "cp packaging/bundler-config #{package_dir}/lib/vendor/.bundle/config"

  # Hack to fix traveling-ruby failing when installed in a path that contains spaces.
  # https://github.com/phusion/traveling-ruby/issues/38
  sh "mv #{package_dir}/lib/ruby/lib/restore_environment.rb #{package_dir}/lib/ruby/lib/ruby/site_ruby/"
  sh <<-eos
    sed -i.bak -e 's|RUBYOPT=\\\\"-r$ROOT/lib/restore_environment\\\\"|RUBYOPT=\\\\"-rrestore_environment\\\\"|' #{package_dir}/lib/ruby/bin/ruby_environment
    sed -i.bak -e 's|GEM_HOME="\\(.*\\)"|GEM_HOME=\\\\"\\1\\\\"|' #{package_dir}/lib/ruby/bin/ruby_environment
    sed -i.bak -e 's|GEM_PATH="\\(.*\\)"|GEM_PATH=\\\\"\\1\\\\"|' #{package_dir}/lib/ruby/bin/ruby_environment
  eos

  # Put in our native dependencies rather than the one provided by bundle
  for native_lib, version in {'json':JSON_VERSION, 'unf_ext':UNF_VERSION} do
    pkg = "packaging/traveling-ruby-#{TRAVELING_RUBY_VERSION}-#{target}-#{native_lib}-#{version}.tar.gz"
    sh "tar -xzf #{pkg} " + "-C #{package_dir}/lib/vendor/ruby"
  end

  if target == "osx"
    sh "mv #{PACKAGE_NAME}-#{VERSION}-osx publishing/darwin/dist"
    if !ENV['NO_PUBLISH']
      sh "cd publishing/darwin; npm publish --access=public -timeout=9999999"
    end
  else
    sh "mv #{PACKAGE_NAME}-#{VERSION}-linux-x86_64 publishing/linux/dist"
    if !ENV['NO_PUBLISH']
      sh "cd publishing/linux; npm publish --access=public -timeout=9999999"
    end
  end
end

def download_runtime(target)
  sh "cd packaging && curl -L -O --fail " +
     "http://d6r77u77i8pq3.cloudfront.net/releases/traveling-ruby-#{TRAVELING_RUBY_VERSION}-#{target}.tar.gz"
end

def download_native_extension(target, gem_name_and_version)
  sh "curl -L --fail -o packaging/traveling-ruby-#{TRAVELING_RUBY_VERSION}-#{target}-#{gem_name_and_version}.tar.gz " +
     "https://d6r77u77i8pq3.cloudfront.net/releases/traveling-ruby-gems-#{TRAVELING_RUBY_VERSION}-#{target}/#{gem_name_and_version}.tar.gz"
end
