#!/usr/bin/ruby

require "getoptlong"

opts = GetoptLong.new(
    [ "--run-time",         "-t", GetoptLong::REQUIRED_ARGUMENT ],
    [ "--device",           "-d", GetoptLong::REQUIRED_ARGUMENT ],
    [ "--max-vol",          "-v", GetoptLong::REQUIRED_ARGUMENT ],
    [ "--keep-current-vol", "-k", GetoptLong::REQUIRED_ARGUMENT ]
)

run_time = 1800
mixer_dev = "PCM"
keep_vol = true
max_vol = 100

opts.each do |opt, arg|
  case opt
  when "--run-time"
    run_time = arg.to_i
    if run_time <= 0 then
      print "--run-time must be a positive, nonzero integer.\n"
      exit(1)
    end
  when "--device"
    mixer_dev = arg
    # should check if device exists.
  when "--keep-current-vol"
    if arg == "yes" then
      keep_vol = true
    elsif arg == "no" then
      keep_vol = false
    else
      print "--keep-current-vol must be \"yes\" or \"no\".\n"
      exit(1)
    end
  when "--max-vol"
    max_vol = arg.to_i
  end
end

# should get current vol

final_vol = 100

sleep_incr = run_time / max_vol

start_time = Time.new
curr_time = start_time
end_time = start_time + run_time
while (curr_time < end_time) do
  sleep(sleep_incr)
  curr_time = Time.new
  time_diff = curr_time - start_time;
  vol = time_diff / run_time * max_vol
  system("amixer", "-q", "set", mixer_dev,  vol.round.to_s + "%")
end