#!/usr/bin/env ruby

require "yaml"

class ProcessMonitor
  SIGNALS = %w[ INT TERM ]

  # The other processes use these, so they stop only once the others have exited
  SERVICES = %w[ redis ]

  def initialize(procfile)
    @procs = process_list(procfile)
    @services, @apps = @procs.partition { SERVICES.include?(it.name) }
    handle_signals

    @procs.each &:start
    wait_until_exited @apps

    @services.each &:terminate
    wait_until_exited @services
  end

  private
    def process_list(procfile)
      config = YAML.load_file(procfile)
      config.map { |name, cmd| MonitoredProcess.new(name, cmd) }
    end

    def handle_signals
      SIGNALS.each do |signal|
        Signal.trap(signal) { stop }
      end

      # A SIGCHLD ignored by whatever started this one would have the kernel reap the children, unseen by the wait
      Signal.trap("CLD", "SYSTEM_DEFAULT")
    end

    # In a container this is PID 1, which also adopts orphans. Waiting for any child reaps them
    # too, and only the exit of one of the processes stops the others.
    def wait_until_exited(processes)
      until processes.all?(&:exited?)
        pid = Process.wait

        if process = @procs.find { it.pid == pid }
          process.mark_exited
          stop
        end
      end
    end

    # Only once: a second TERM tells resque-pool to stop waiting for its workers
    def stop
      unless @stopping
        @stopping = true
        @apps.each &:terminate
      end
    end
end

class MonitoredProcess
  attr_reader :name, :pid

  def initialize(name, cmd)
    @name, @cmd = name, cmd
  end

  # In a process group of its own, so a Ctrl-C in a terminal reaches only bin/boot, which stops everything in order
  def start
    @pid = Process.spawn(@cmd, pgroup: true)
  end

  def mark_exited
    @exited = true
  end

  def exited?
    @exited
  end

  # Once reaped, its pid may already belong to another process
  def terminate
    Process.kill "TERM", @pid unless exited?
  end
end

ProcessMonitor.new("Procfile")
