#!/usr/bin/env ruby
require 'pry'
require 'yaml'
require 'active_support/all'

shared_dir = Pathname.new File.expand_path('../../', __FILE__)
app_dir = Pathname.new File.expand_path('../', __FILE__)
class Runner
  def execute(cmd)
    puts "Running: #{cmd}"
    `#{cmd}`
  end
end

runner = Runner.new

prefix = "mozo_"
containers = YAML.load <<-YML.strip_heredoc
  drb_counter:
    directory: drb_counter
    volumes:
    - #{app_dir.join('config')}:config
    ports:
    - 9022
    arguments:
    - production
  faye:
    directory: faye
    ports:
    - 9296
YML
container_names = containers.keys.map{|c| [prefix, c].join }
#container_name_list = container_names.join(' ')

#REBUILD
containers.each do |name, settings|
  runner.execute "docker build -t #{prefix}#{name} #{settings['directory']}"
end

running_containers = runner.execute("docker ps -q #{container_names.map{|cname| "-f name=#{cname}" }.join(' ')}").to_s.strip.split(/\s+/)
runner.execute("docker stop #{running_containers.join(' ')}") if running_containers.any?

existing_containers = runner.execute("docker ps -a -q #{container_names.map{|cname| "-f name=#{cname}" }.join(' ')}").to_s.strip.split(/\s+/)
runner.execute("docker rm #{existing_containers.join(' ')}") if existing_containers.any?

# RUN THE CONTAINERS
containers.each do |name, settings|
  volumes = Array.wrap(settings['volumes']).map{|v| "-v #{v}"}.join(' ')
  arguments = Array.wrap(settings['arguments']).join(' ')
  runner.execute "docker run -d --net=host --restart=always #{volumes} --name=#{prefix}#{name} #{prefix}#{name} #{arguments}"
end
