#!/usr/bin/ruby
#
# Clunky Ruby script to build the P4Ruby distribution. Horrible, but it works
# so it'll do for now.
#
require "ftools"

def get_version
  v = nil
  File.open( "p4rb_version.h" ) do
    |f|
    f.each do
      |line|
      if ( line =~ /^#\s*define\s+P4RUBY_VERSION\s+\"(\d+\.\d+)\"/ )
	v = $1
	break
      end
    end
  end
  if ( ! v )
    raise( RuntimeError, "Can't figure out the version of P4Ruby!" )
  end
  return v
end

def makedirs( file )
  dirs = file.split( /\// )
  dirs.pop
  p = nil
  dirs.each do
    |d|
    if( p )
      p += "/#{d}"
    else
      p = d
    end
    if( File.exists?( p ) )
      if( !File.directory?( p ) )
	raise( RuntimeError, "Can't make #{p}: already exists and not a directory!" )
      end
    else
      Dir.mkdir( p )
    end
  end
end


def filecopy( srcpath, dstdir )
  dstpath = dstdir + "/" + srcpath
  makedirs( dstpath )
  File.copy( srcpath, dstpath )
end

def populate( build_dir )
  Dir.mkdir( build_dir ) or raise( RuntimeError, "Can't create #{build_dir}" )
  mfest = File.open( "MANIFEST" )
  files = mfest.readlines()
  mfest.close
  files.each do
    |file|
    file.sub!( /\r?\n/, "" )
    filecopy( file, build_dir )
  end
end

def build_tarball( build_dir )
  system( "tar zcvf #{build_dir}.tar.gz #{build_dir}" )
end

def cleanup( build_dir )
  if File.directory?( build_dir )
    system( "rm -rf #{build_dir}" )
  end
end

version = get_version()
build_dir = "P4Ruby-" + version
cleanup( build_dir )
populate( build_dir )
build_tarball( build_dir )
cleanup( build_dir )