#!/usr/bin/env ruby

require 'airstream'

def self.exit(status)
  Airstream::Io.show_input
  puts "\n" # clear output
  super status
end

options = {
  receiver: '192.168.0.123',
  quiet: false,
  verbose: false,
  # disable_local_http: true
  interval: 3
}

EXIT_OK = 0
EXIT_ERROR = 1
EXIT_NO_HOST = 68

CONFIG_FILE = File.join(ENV['HOME'] || '', '.airstreamrc')

if File.exists? CONFIG_FILE
  options_config = YAML.load_file(CONFIG_FILE)
  options.merge!(options_config)
end

option_parser = OptionParser.new do |opts|
  executable_name = File.basename($PROGRAM_NAME)
  opts.banner = "offer a image file to an airplay device

Usage: #{executable_name} [options] [url|path/]filename

Basic options: (configure default in ~/.airstreamrc)
"
  opts.on("-o RECEIVER",
   "the airplay-device ip-address or domain") do |receiver|
    options[:receiver] = receiver
  end

  opts.on("-n SECONDS", "--interval SECONDS",
   "seconds between switching image files") do |interval|
    options[:interval] = interval.to_i
  end

  opts.on("-v", "--version",
   "output version information then quit") do |path|
    puts "airstream airimg v" + Airstream::VERSION
    exit 0
  end
end

if ARGV.empty?
  STDERR.puts "No arguments given"
  STDERR.puts option_parser
  exit 1
end

begin
  option_parser.parse!

  unless options[:receiver]
    STDERR.puts "No host given"
    exit 68
  end

  node = Airstream::Node.new options[:receiver]
  device = Airstream::Device.new node

  io = Airstream::Io.new
  io.quiet = options[:quiet]
  io.verbose = options[:verbose]
  io.puts "=> press ["+Airstream::Io::KEY_QUIT+"] to exit airstream"
  Airstream::Io.hide_input
  ARGV.each do |file|
    device.image = file
    sleep options[:interval]
    io.catch_input
    break if io.quit?
  end


rescue Interrupt
  STDERR.puts
  STDERR.puts "exiting"
  exit EXIT_OK
rescue OptionParser::InvalidArgument => ex
  STDERR.puts ex.message
  STDERR.puts option_parser
  exit EXIT_ERROR
ensure
  Airstream::Io.show_input
end

exit EXIT_OK
