#
# Cookbook Name:: kosmos-parity
# Recipe:: create_package_from_github
#
# The MIT License (MIT)
#
# Copyright:: 2019, Kosmos Developers
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

include_recipe 'kosmos-parity::user'
include_recipe 'build-essential'
package %w(git libssl-dev pkg-config libudev-dev)
gem_package 'fpm' do
  version '1.8.1'
end

rust_version = '1.17.0'
architecture = node['kernel']['machine']
rust_canonical_basename = "rust-#{rust_version}-#{architecture}-unknown-linux-gnu"
rust_path = "/usr/local/rust_#{rust_version}"

url = "https://static.rust-lang.org/dist/#{rust_canonical_basename}.tar.gz"

ark "rust_#{rust_version}" do
  url      url
  path     "/usr/local"
  action   :put
  notifies :run, "execute[install rust]", :immediately
end

execute "install rust" do
  command "./install.sh"
  cwd     "#{rust_path}"
  action  :nothing
end

parity_revision = "0d8920347a72fc50e82b540855eba94c8bbb2c0f"

git "/home/parity/parity" do
  repository "https://github.com/paritytech/parity.git"
  revision   parity_revision
  user       "parity"
  group      "parity"
  notifies :run, "execute[build parity]", :immediately
end

execute "build parity" do
  cwd         "/home/parity/parity"
  environment "HOME" => "/home/parity"
  command     "cargo build --release"
  action      :nothing
  user        "parity"
  group       "parity"
  notifies    :run, "execute[copy parity]", :immediately
end

execute "copy parity" do
  command  "cp /home/parity/parity/target/release/parity /usr/bin/"
  action   :run
  notifies :run, "execute[create package]", :immediately
end

timestamp = Time.now.strftime('%s')
parity_version  = node['kosmos-parity']['package_version']
execute "create package" do
  cwd     node['kosmos-parity']['debian_package_dir']
  command "fpm -s dir -t deb -n parity -v #{parity_version}-#{timestamp} -p parity_#{parity_version}-#{timestamp}.deb /usr/bin/parity"
  action  :nothing
end
