#!/usr/bin/env ruby

# Controller Daemon

# $Id: controller.rb,v 1.16 2002/05/13 23:07:26 kenji Exp $

# 2002/4/30  Ken-ichi HASHIMOTO <ken@po.ganseki.ne.jp>
# Copyright (C) 2002 Ken-ichi HASHIMOTO <ken@po.ganseki.ne.jp>
# This is free software with ABSOLUTELY NO WARRANTY.

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.


baseDir = File.expand_path(File.dirname(__FILE__)+"/../")
binDir  = baseDir + "/bin"
libDir  = baseDir + "/lib"
varDir  = baseDir + "/var"
confDir = baseDir + "/conf"
logsDir = baseDir + "/logs"
filesDir = baseDir + "/video_files"

$: << libDir


class ProgramItem
	attr_accessor :starttime	#Time
	attr_accessor :endtime		#Time
	attr_accessor :channel		#String
	attr_accessor :quality		#String
	attr_accessor :filename		#String
end


## TODO クラスライブラリに分離
class Logger
	def debug( aLevel , aString )
		print aString
	end
	def info( aLevel , aString )
		print aString
	end
end
logger = Logger.new
logger.info( 0 , "Controller.rb Start\n")


readyTime = 45   # 45 sec
recording = false
recorder = "/usr/local/bin/DIVX4rec"
programListFile = varDir + "/program_list" 


require 'reservation_generator'
loop do
	programList = Array.new

	startday = Time.now
	endday = Time.at( startday.to_i + 60*60*24*1 )
	reservationList = ReservationList.new
	reservationList.loadFrom( programListFile )
	reservationGenerator = ReservationGenerator.new
	reservationGenerator.setReservationList(reservationList)

	reservationGenerator.createBetween(startday,endday).each do |line|
		next unless (line =~ /.+\s+.+\s+.+\s+.+\s+.+\s+.+\s+.+/ )

		item = ProgramItem.new
		ary = line.chomp.split(/\s+/)

		ymd = ary[0].split( /\// )
		hms = ary[1].split( /:/ )
		item.starttime = Time.local( ymd[0] , ymd[1] , ymd[2] , hms[0] , hms[1] , hms[2] );

		ymd = ary[2].split( /\// )
		hms = ary[3].split( /:/ )
		item.endtime = Time.local( ymd[0] , ymd[1] , ymd[2] , hms[0] , hms[1] , hms[2] );

		item.channel = ary[4]
		item.quality = ary[5]
		item.filename= ary[6]

		programList << item
	end

	sortedProgramList = programList.sort { |a,b| b.starttime<=>a.starttime }
	now = Time.now.to_i 

	theProgram = nil
	sortedProgramList.each do |item|
		if (now > item.starttime.to_i - readyTime) && (now < item.endtime.to_i)
			theProgram = item
			break;
		end
	end

	if !theProgram then
		recording = false
	end

	if theProgram && !recording then
		stime = theProgram.starttime.strftime('%S:%M:%H:%d:%m:%y')
		etime = theProgram.endtime.strftime('%S:%M:%H:%d:%m:%y')

		# channel frequency and other options
		cfg = nil
		open("#{confDir}/channel.conf") do |file|
			file.each do |line|
				next unless (line =~ /(\S+)\s+(\S+)/ )
				ary = line.chomp.split(/\s+/,2)
				channel = ary[0]
				option = ary[1]

				if theProgram.channel == channel then
					cfg = "#{confDir}/#{theProgram.quality}.conf #{option}"
				end
			end
		end
		if cfg == nil then
			printf "Error: channel #{theProgram.channel} is invalid.\n"
			exit;
		end

		# logging
		log_time = Time.now.strftime("%Y/%m/%d:%H:%M:%S")
		start_time = theProgram.starttime.strftime("%H:%M:%S")
		end_time = theProgram.endtime.strftime("%H:%M:%S")
		open("#{logsDir}/timer.log", "a") do |log|
			log << "[#{log_time}] DIVX4 #{start_time} #{end_time} #{theProgram.channel} #{theProgram.quality} #{theProgram.filename}\n"
		end


		logfile = theProgram.filename.gsub(/\//,'_')
		recording = true
		logger.info( 0 , "Controller.rb Start timer.rb\n")
		system("#{binDir}/prerec.sh") if FileTest.executable?( "#{binDir}/prerec.sh" )
		system("#{binDir}/timer.rb #{stime} #{etime} #{recorder} -C #{cfg} -o #{filesDir}/#{theProgram.filename} 2> #{logsDir}/dmesg.#{logfile}")
		recording = false
		logger.info( 0 , "Controller.rb timer.rb finished\n")
	else
		sleep 30
	end
end

