#!/usr/bin/ruby

require 'fileutils'

if ARGV.length != 2
  puts "usage: test-package [OPTIONS] PACKAGE OUTPUTDIR"
  exit 1
end

pkg = ARGV.shift
outdir = ARGV.shift

FileUtils.mkdir(outdir)
if ENV["DEBCI_FAKE_DEPS"]
  File.open(File.join(outdir, 'foo0t-mytest-packages'), 'w') do |f|
    ENV["DEBCI_FAKE_DEPS"].split('|').each do |line|
      f.puts line.gsub(" ", "\t")
    end
  end
end

if ENV["DEBCI_FAKE_COMMAND"]
  io = IO.popen(ENV["DEBCI_FAKE_COMMAND"])
  log = [ '$ ' + ENV['DEBCI_FAKE_COMMAND'], io.read].join("\n")
  io.close
  rc = $?.exitstatus
  if rc != 0
    rc = 4
  end
else
  puts "Not really running anything .."
  puts "This will fail, pass or tmpfail randomly. Passing is twice as probable as fail and tmpfail"

  r = nil
  case ENV['DEBCI_FAKE_RESULT']
  when 'pass'
    r = 0
  when 'fail'
    r = 2
  when 'tmpfail'
    r = 3
  else
    r = rand(4)
  end

  case r
  when 0..1
    log = "Passed :-)\n"
    rc = 0
  when 2
    log = "Failed :-(\n"
    rc = 4
  when 3
    log = "Some error ocurred\n"
    rc = 16
  end
end

if ENV["DEBCI_FAKE_KILLPARENT"]
  # find our parent which is the t
  p = Process.pid
  while p > 1
    File.open("/proc/#{p}/stat") do |f|
      stat = f.gets.split()
      if stat[1].include? ENV["DEBCI_FAKE_KILLPARENT"]
        # got it, kill that
        Process.kill('FPE', p)
        p = -1
      else
        p = Integer(stat[3])
      end
    end
  end
end

log = log + "adt-run [%s]: finished\n" % Time.now.strftime('%Y-%m-%d %H:%M:%S')

File.open(File.join(outdir, 'log'), 'w') do |f|
  f.puts log
end
File.open(File.join(outdir, 'exitcode'), 'w') do |f|
  f.puts rc
end
puts log
exit rc
