#!/usr/bin/env ruby
raise 'Please, use ruby1.8.4 or later.' if RUBY_VERSION < '1.8.4'
=begin

 Rantfile example for making a simple debian package of a ruby program
 using git-buildpackage with debuild

 Copyright (C) 2007 Ralph Amissah

 * License: LGPL - GNU Lesser General Public License
     [same license as Rant provided within the Rant package]

 * Ralph Amissah <ralph@amissah.com>
   Ralph Amissah <ralph.amissah@gmail.com>

 Rant is a Ruby 'ant' by Stefan Lang
 * Rant may be downloaded and installed from:
     http://make.rubyforge.org/

 Notes on use:

 This Rantfile is used in conjunction with the rantrc.yml example provided
 (example is easily extended and works for package rant, and package diakonos)

 * package should be in directory with package name without package version
   number
 * Rantfile and rantrc.yml should be in directory above package directory,
   e.g. for rant ls
     Rantfile, rantrc.yml rant/

 * provide details of package in rantrc.yml file [which is a yaml file] (see
   example provided)

 * once these two files are in place for help on package and on possible
   actions, enter:
     rant
     rant info
     rant -T

 * NOTE to create independent rant independent ruby script:
     rant-import --auto [provide name of ruby (rant exported) script]

=end
#%% produce a makefile suitable for the target platform
#require 'mkmf'
#create_makefile("sisu")
require 'pkgrc'
include RC
@pkg=RC::Package.new
p @pkg.pwd
@rant_desc="Rantfile for debian git-buildpackage of: #{@pkg.aka}"
u=`whoami`
i=`id`
if u =~/root/ or i =~/root/ or i=~/(?:uid|gid|groups)=0[^\d]/
  puts "This build program is NOT to be run as root.\n\n"
  exit
end
def pkg_info
  @pkg.pkg_info
end
def home_750
  system("chmod 750 #@home")
end
def home_755
  system("chmod 755 #@home")
end
def mv_dir_pkg_to_pkg_and_version #not used
  if File.directory?(@pkg.name)
    system(%{
      mv #{@pkg.name} #{@pkg.name_up}
    })
  else exit
  end
end
def mv_dir_pkg_and_version_to_pkg #not used
  if File.directory?(@pkg.name_up)
    system(%{
      mv #{@pkg.name_up} #{@pkg.name}
    })
  else exit
  end
end
def answer?(ask)
  response='redo'
  print ask + " ['yes', 'no' or 'quit']: "
  response=File.new('/dev/tty').gets.strip
  #response=gets.strip
  ans=if response == 'yes'; true
  elsif response == 'no'; false
  elsif response =~/^quit|exit$/; exit
  else puts "[please type: 'yes', 'no' or 'quit']"
    answer?(ask)
  end
  ans
end
def signed?
  response=answer?(%{create a signed debian package?: yes [or no for unsigned]: })
  puts '---'
  @sign=if response
    #system(@gpg[:mount]) if @gpg[:mount] and not @gpg[:mount].empty?
    #puts response
    true
  else false
  end
end
def cd_umount
  system('umount /cdrom')
  puts 'unmount sd - PLEASE REMOVE CD-ROM'
end
def git_co_upstream
  system(%{
    cd #{@pkg.name}
    echo "git-checkout #{@pkg.git_up}"
    git-checkout #{@pkg.git_up}
  })
end
def git_co_debian
  system(%{
    cd #{@pkg.name}
    echo "git-checkout #{@pkg.git_deb}"
    git-checkout #{@pkg.git_deb}
  })
end
def git_commit(commit_message)
  system(%{
    cd #{@pkg.name}
    git-commit -a -m"#{commit_message}"
  })
end
def git_merge_upstream
  git_co_debian
  system(%{
    cd #{@pkg.name}
    git-diff upstream
    git-status
  })
  response=answer?(%{merge upstream?: yes or no to skip: })
  puts "--- #{response} ---"
  if response
    system(%{
      cd #{@pkg.name}
      git-merge upstream
    })
  end
end
def gitignore
ignore=<<WOK
# git-ls-files --others --exclude-from=.git/info/exclude
# Lines that start with '#' are comments.
# For a project mostly in C, the following would be a good set of
# exclude patterns (uncomment them if you want to use them):
# *.[oa]
InstalledFiles
.config
.*.sw?
*~
\#*#
.#*
,,*
*[._]bk
*[._]old
tst*
#test*
RCS
WOK
  system(%{
    if [[ -e "#{@pkg.name}/.git/info/exclude" ]]; then
      echo "replacing gitignore, exclude file"
    else
      echo "creating gitignore, exclude file"
    fi
    echo "#{ignore}" > #{@pkg.name}/.git/info/exclude
  })
end
def clean_waste
  system(%{
    rm -v */**/*.sw?
    rm -v */**/.*.sw?
    rm -v */**/*~
  })
end
def default_notice #package_reminder
  response=''
  while response !~/^[yn]$/
    print %{#{@rant_desc}
  Information on alternative actions is available using:
    "rant help" or "rant -T"
  Default action selected - "debianise #{@pkg.name_up}" (using git-buildpackage) proceed? [y/n]: }
    response="y\n" #response=File.new('/dev/tty').gets.strip
    exit if response =~/^(n|quit)$/
  end
  if response =~/^n$/
    while response !~/^[yn]$/
      print %{do you wish to edit CHANGELOG (& README) now? to edit [y], to abandon package-build [n]: }
      exit if response =~/^(n|quit)$/
    end
    system(" vim #{@pkg.name}/{CHANGELOG,README} ") if response.include? ?y
  end
end
def dch
  p @pkg.version_deb
  @dch=if @pkg.version_deb; "debchange -v #{@pkg.version_deb}"
  else                   'debchange -a'
  end
  #@dch='debchange -i'
end
def dch_news(news=false)
  @dch_news=if news; 'debchange --news'
  else ''
  end
  #@dch='debchange -i'
end
def dchi
  p @pkg.version_deb
  @dch=if @pkg.version_deb; "debchange -v #{@pkg.version_deb}"
  else                   'debchange -i'
  end
end
def pkg_git                                                          #% everything happens here
  if File.directory?(@pkg.name)
    buildpackage=if @sign; %{git-buildpackage -D -i\.git -I.git --git-upstream-branch="#{@pkg.git_up}" --git-debian-branch="#{@pkg.git_deb}" --git-tag}     #build package, signed check dependencies
    else            %{git-buildpackage -us -uc -D --git-upstream-branch="#{@pkg.git_up}" --git-debian-branch="#{@pkg.git_deb}"}               #build package, no signing check dependencies
    end
    gitignore
    system(%{
      cd #{@pkg.name}
      git-checkout #{@pkg.git_deb}
      rm -v **/\.*                                                   #does not remove .git which is a directory [edit out, not everyone will want this] [zsh specific not bash]
      #@dch                                                          #update debian version number
      git add . && git commit -a -m "Updated #{@pkg.name_up}"           #version changes
      #{buildpackage}
      debuild clean
      cd -
    })
    echo_build_output
  else puts "directory NOT FOUND: #{@pkg.name}"
  end
end
def echo_build_output
  system(%{
    #ls -hoS #{@pkg.name}*#{@pkg.version_deb}*.deb
    echo 'source ---'
    ls -sh1  #{@pkg.name}*#{@pkg.version_deb}*.dsc #{@pkg.name}*#{@pkg.version_project}*.tar.gz #{@pkg.name}*#{@pkg.version_deb}*.diff.gz
    echo 'deb    ---'
    ls -shS1 #{@pkg.name}*#{@pkg.version_deb}*.deb
  })
end
def git_checkpoint #not used
  unless @tag =~/^quit$/i
    puts %{git tag --patch-name="#{@week_slash_day} #@tag" --checkpoint\n}
    system(%{
      cd #{@pkg.name}
      git tag --patch-name="#{@week_slash_day} #@tag" --checkpoint
      cd -
    })
  end
end
def changes
  changes=`cat #{@pkg.name}*.changes`
  p changes
  changes
end
def debian_files #in case you need it, should be automatically handled by dch ... remove
  pwd=Dir.pwd
  system(%{echo "#{@pkg.name}_#{@pkg.version_project}_all.deb text extra
#{@pkg.name}-examples_#{@pkg.version_project}_all.deb text extra" > #{pwd}/#{@pkg.name}-#{@pkg.version_project}/debian/files
})
end
def reprepro
  changes=`ls #{@pkg.name}_#{@pkg.version_deb}*.changes`
  unless changes.nil? or changes.empty?
    system(%{reprepro -Vb #{@pkg.reprepro_path} include #{@pkg.reprepro_branch} #{changes}})
  end
end
def dpkg_install
  echo_build_output
  system("
    #sudo dpkg -i `echo #{@pkg.name}*#{@pkg.version_deb}*.deb`
  ")
end
def remote_host
  system(%{
    rsync -av --delete-after #{@pkg.reprepro_path}/{dists,pool} #{@pkg.remote_apt_archive}/.
  })
end
def pwd
  puts 'ruby: ' + Dir.pwd
  system(%{echo "zsh:  $PWD"})
end
def deb_dir_skel
  def control
<<WOK
Source: #{@pkg.name_up}
Section: devel
Priority: optional
Maintainer: #{@pkg.maintainer} #{@pkg.maintainer_email}
Build-Depends: debhelper (>= 5)
Standards-Version: 3.7.2

Package: #{@pkg.name}
Architecture: all
Depends: ruby (>= 1.8.2)
Description: [---]
 [---]
 .
  Homepage: <http://url/>
WOK
  end
  def rules
<<WOK
#!/usr/bin/make -f
#export DH_VERBOSE=1

build:

clean:
	dh_testdir
	dh_testroot
	dh_clean

install: build
	dh_testdir
	dh_testroot
	dh_clean -k
	dh_installdirs

binary-arch: build install

binary-indep: build install
	dh_testdir
	dh_testroot
	dh_installdocs README
	dh_installchangelogs CHANGELOG
	dh_installman
	dh_install
	dh_compress
	dh_fixperms
	dh_installdeb
	dh_gencontrol
	dh_md5sums
	dh_builddeb

binary: binary-indep binary-arch
.PHONY: clean build install binary-indep binary-arch binary
WOK
  end
  def compat
   '5'
  end
  def copyright
<<WOK
This is #{@pkg.name}, written and maintained by Ralph Amissah <ralph@amissah.com>
on Mon, 2 May 2005 17:33:58 +0100.

The homepage is:
  <http://www.jus.uio.no/sisu>

The original source can always be found at:
	<http://www.jus.uio.no/sisu/SiSU/download>
	<http://www.jus.uio.no/sisu/pkg/src>

Copyright (C) 1997, 1998, 1999, 2000, 20001, 2002, 2003, 2004, 2005
Ralph Amissah

License: GPL 2 or later

  GPL2 summary:

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this package; if not, write to the Free Software
  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  MA 02110-1301, USA

  If you have Internet connection, the latest version of the GPL should be
  available from these locations:
    <http://www.fsf.org/licenses/gpl.html>
    <http://www.gnu.org/copyleft/gpl.html>
    <http://www.jus.uio.no/sisu/gpl2.fsf>

  On Debian systems, the complete text of the GNU General
  Public License can be found in `/usr/share/common-licenses/GPL'.

  The Free Software Foundation:
    <http://www.fsf.org/>
WOK
  end
  def install
    bin=if File.directory?("#{@pkg.pwd}/#{@pkg.name}/bin")
      "bin/ usr\n"
    else ''
    end
    lib=if File.directory?("#{@pkg.pwd}/#{@pkg.name}/lib")
      if File.directory?("#{@pkg.pwd}/#{@pkg.name}/lib/#{@pkg.name}")
        "lib/#{@pkg.name} usr/lib/ruby/1.8\n"
      else
      end
    else ''
    end
    conf=if File.directory?("#{@pkg.pwd}/#{@pkg.name}/conf/#{@pkg.name}")
      "conf/#{@pkg.name} etc\n"
    else ''
    end
    if File.directory?("#{@pkg.pwd}/#{@pkg.name}/data")
      if File.directory?("#{@pkg.pwd}/#{@pkg.name}/data/#{@pkg.name}") or File.directory?("#{@pkg.pwd}/#{@pkg.name}/data/doc")
        share=if File.directory?("#{@pkg.pwd}/#{@pkg.name}/data/#{@pkg.name}")
          "data/#{@pkg.name} usr/share\n"
        else ''
        end
        doc=if File.directory?("#{@pkg.pwd}/#{@pkg.name}/data/doc/#{@pkg.name}")
          "data/doc/#{@pkg.name} usr/share/doc\n"
        elsif File.directory?("#{@pkg.pwd}/#{@pkg.name}/data/doc")
          "data/doc/ usr/share/doc/#{@pkg.name}\n"
        else ''
        end
      else
      end
    elsif File.directory?("#{@pkg.pwd}/#{@pkg.name}/share")
      if File.directory?("#{@pkg.pwd}/#{@pkg.name}/share/#{@pkg.name}") or File.directory?("#{@pkg.pwd}/#{@pkg.name}/share/doc")
        share=if File.directory?("#{@pkg.pwd}/#{@pkg.name}/share/#{@pkg.name}")
          "share/#{@pkg.name} usr/share\n"
        elsif File.directory?("#{@pkg.pwd}/#{@pkg.name}/share/doc")
          "data/doc/ usr/share/doc/#{@pkg.name}\n"
        else ''
        end
        doc=if File.directory?("#{@pkg.pwd}/#{@pkg.name}/share/doc/#{@pkg.name}")
          "share/doc/#{@pkg.name} usr/share/doc\n"
        elsif File.directory?("#{@pkg.pwd}/#{@pkg.name}/share/doc")
          "data/doc/ usr/share/doc/#{@pkg.name}\n"
        else ''
        end
      else
      end
    elsif File.directory?("#{@pkg.pwd}/#{@pkg.name}/doc")
      doc=if File.directory?("#{@pkg.pwd}/#{@pkg.name}/doc/#{@pkg.name}")
        "doc/#{@pkg.name} usr/share/doc\n"
        #"doc/ usr/share/doc/#{@pkg.name}"
      else "doc usr/share/doc/#{@pkg.name}\n"
      end
    else ''
    end
    "#{bin}#{lib}#{conf}#{share}#{doc}"
  end
  def manpages
    man_1=if File.exist?("#{@pkg.pwd}/#{@pkg.name}/man/man1/#{@pkg.name}.1")
      "man/man1/#{@pkg.name}.1\n"
    else ''
    end
    man_7=if File.exist?("#{@pkg.pwd}/#{@pkg.name}/man/man7/#{@pkg.name}.7")
      "man/man7/#{@pkg.name}.7\n"
    else ''
    end
    man_8=if File.exist?("#{@pkg.pwd}/#{@pkg.name}/man/man8/#{@pkg.name}.8")
      "man/man8/#{@pkg.name}.8\n"
    else ''
    end
    "#{man_1}#{man_7}#{man_8}"
  end
  def readme_debian #README.Debian
  end
  def changelog
<<WOK
#{@pkg.name} (#{@pkg.version_deb}) unstable; urgency=low

  * Initial release. (Closes: #XXXXXX)

 -- #{@pkg.maintainer} #{@pkg.maintainer_email}  Mon, 25 Jun 2007 01:47:21 +0100
WOK
  end
  self
end
def deb_dir_init
  puts %{
    if branch debian/sid does not already exist, create it from upstream git-checkout -b #{@pkg.git_deb} [personal preference "debian/sid"]
    if no debian directory, create it, mkdir -p #{@pkg.name}/debian
    if no initial files, create them, else abandon task, exit.
  }
  system(%{
    cd #{@pkg.name}
    current_dir=`pwd`
    git-checkout #{@pkg.git_up}
    git-checkout -b #{@pkg.git_deb}
    git-checkout #{@pkg.git_deb}
    if [[ -e "$current_dir/debian" ]]; then
      #dir_exits=true
      ls -la "$current_dir/debian"
    else
      mkdir -pv "$current_dir/debian"
    fi
    cd -
  })
  debian_files=['control','rules','changelog','copyright','compat','install','manpages']
  debian_files.each do |file|
    if FileTest.exist?("#{@pkg.pwd}/#{@pkg.name}/debian/#{file}")
      puts "initialization process aborted, file #{file} already exits\n\n"
      exit
    end
  end
  debian_files.each do |file|
    debian_file=File.new("#{@pkg.pwd}/#{@pkg.name}/debian/#{file}",'w')
    case file
    when /control/;   debian_file << deb_dir_skel.control
    when /rules/;     debian_file << deb_dir_skel.rules
    when /changelog/; debian_file << deb_dir_skel.changelog
    when /copyright/; debian_file << deb_dir_skel.copyright
    when /compat/;    debian_file << deb_dir_skel.compat
    when /install/;   debian_file << deb_dir_skel.install
    when /manpages/;  debian_file << deb_dir_skel.manpages
    end
    debian_file.close
    puts "create #{file}"
  end
  system("chmod 755 #{@pkg.pwd}/#{@pkg.name}/debian/rules")
end
def rant_to_ruby
  system(%{
    if [[ -e "#{@pkg.pwd}/deb_rb_pkg_#{@pkg.name}" ]]; then
      echo "
      deb_rb_pkg_#{@pkg.name}: filename already exists
      #{@pkg.pwd}/deb_rb_pkg_#{@pkg.name}
      please remove it and repeat command to proceed
      "
    else
      rant-import --auto deb_rb_pkg_#{@pkg.name}
      chmod 755 deb_rb_pkg_#{@pkg.name}
      ls -la deb_rb_pkg_#{@pkg.name}
    fi
  })
end
def rant_system_info
  puts <<WOK
  Host
    host:             #@host
    arch:             #{@sys_arch}
    sitearch:         #{@sys_sitearch}

  Directories for installation
    bin:                                          #{@pkg.dir_bin}
    lib (site-ruby):                              #{@pkg.dir_lib}/#{@pkg.name}/#{@pkg.version_base}
    conf [etc]:                                   #{@pkg.dir_conf}/#{@pkg.name}
    data (document samples, images, README):      #{@pkg.dir_data}/#{@pkg.name}  and  #{@pkg.dir_data}/doc/#{@pkg.name}
    man (manual pages):                           #{@pkg.dir_man}
    output:                                       #{@pkg.dir_output}
      processing:                                 #{@pkg.dir_output}/processing
      www:                                        #{@pkg.dir_output}/www

    rubylib:          #@rubylib

WOK
end
def rant_help
  puts <<WOK

#{@rant_desc}

For information on the package:          rant info

For a list of command options use:       rant -T

WOK
end
                                                           #% tasks
task :default => [:help]
desc "info on package"
task :info => [:info]
task :i => [:info]
desc "help for Rantfile to make debian package (using git-buildpackage) & apt archive"
task :h => [:help]
task :w => [:what]
task :what => [:what]
desc "project description"
task :which => [:what]
task :dbp => [:pkg]
task :package => [:pkg_git]
desc "git build package - make debian package"
task :pkg => :pkg_git
task :pkg_git => [:pre_pkg_git,:dch,:package_git,:post_pkg]
desc "git build package and add NEWS file - make debian package"
task :pkg_news => [:pre_pkg_git,:dch_news,:package_git,:post_pkg]
desc "bump sisu version from pkgrc.yml"
desc "man 2 html"
task :man2html => [:man_html]
desc "copy apt repo online"
task :remote_host => [:remote_host]
desc "install resulting debs if any, dpkg -i `echo *[version-number]*.deb`"
task :dpkgi => [:dpkg_install]
desc "bump up @pkg.name version"
desc "checkpoint git repository"
task :checkpoint => [:git_checkpoint]
desc "dgst info"
task :dgst => [:changes]
desc "make tarball"
task :tgz => [:tgz_mk]
desc "update apt-archive using reprepro"
task :reprepro => [:reprepro]
desc "system info"
task :system_info => [:system_info]
desc "initialise skeleton debian directory for a typical simple ruby application"
task :deb_dir_init => [:deb_dir_init]
desc "system parameters seen by ruby"
task :system_param => [:system_param]
task :pwd => [:pwd]
desc "create new ruby executable version of Rantfile deb_rb_pkg_[name]"
task :rant_to_ruby => [:rant_to_ruby]
desc "rdoc"
task :rdoc => [:rdoc]
#                                                           #%% dars / depackage / git-buildpackage tasks
task :info do
  pkg_info
end
task :package_notices do
  default_notice
end
task :man_html do
  man2html
end
task :dch do
  dch
  dch_news(false)
end
task :dch_news do
  dch
  dch_news(true)
end
task :dchi do
  dchi
end
#task :package do
#  pkg_git
#end
task :package_git do
  pkg_git
end
#task :cleanup do
#  clean
#end
task :changes do
  changes
end
task :reprepro do
  reprepro
end
task :remote_host do
  remote_host
end
task :remote_host_exp do
  remote_host_experimental_package
end
task :pre_pkg_generic do
  home_755
  signed?
  update_sisu_rant_installer
end
task :pre_pkg_git do
  home_755
  puts "  will checkout upstream, update and commit CHANGELOG and version files;
  will checkout debian directory, attempt to merge upstream, and then;
  will attempt to build package;\n
  if you have not already done so, you may *now* wish to:
  * update package the version in the pkg.yml file
  * edit the CHANGELOG (& README)\n\n"
  #mv_dir_pkg_to_pkg_and_version
  signed?
  git_co_upstream
  git_commit('changelog and version updated')
  git_co_debian
  git_merge_upstream
end
task :post_pkg do
  cd_umount
  home_750
  #mv_dir_pkg_and_version_to_pkg
end
task :dpkg_install do
  dpkg_install
end
task :pwd do
  pwd
end
task :system_info do
  rant_system_info
end
task :system_param do
  Config::CONFIG.each {|c| p c }
end
task :deb_dir_init do
  deb_dir_init
end
task :rant_to_ruby do
  rant_to_ruby
end
task :rdoc do
  rdoc
end
task :help do
  rant_help
end
__END__
