<?php
    include 'constants.php';
    require_once 'includes/util.php';    
 
    if (!defined("ENABLE_ATSC_INPUT"))
        define("ENABLE_ATSC_INPUT", 0);
    if (!defined("ENABLE_DVBS_INPUT"))
        define("ENABLE_DVBS_INPUT", 0);           

    function get_scan_log($tunerIndex) {
        return "/var/tmp/dvbapi_scan{$tunerIndex}.log";
    }
    
    function get_scan_cmd($tunerIndex) {
        return "scan -a{$tunerIndex} /usr/share/dvb/dvb-legacy/atsc/us-ATSC-center-frequencies-8VSB";
    }
    
    function scan_is_running($tunerIndex = null) {
        exec("sudo ps -o args -C scan", $execOutput, $execReturn);
        if (0 != $execReturn) {
            return false;
        }
        
        foreach ($execOutput as $line) {
            if (!preg_match("/scan \-a([0-9]+) \/usr\/.*/", $line, $output_array)) {
                continue;
            }
            
            if (count($output_array) != 2) {
                continue;
            }
            
            $scanningTuner = $output_array[1];
            if (is_numeric($scanningTuner)) {
                if (is_int($tunerIndex)) {
                    $scanningTuner = (int)$scanningTuner;
                    if ($scanningTuner == $tunerIndex) {
                        return true;
                    }
                } else {
                    return true;
                }
            }            
        }
        
        return false;
    }
    
    if (!ENABLE_ATSC_INPUT && !ENABLE_DVBS_INPUT)
        exit();
    
    require_once 'includes/dvbapi.php';
    
    $atscAdapters = dvbapi_listAdapters();                                            
    if (!$atscAdapters || !count($atscAdapters)) {
        echo "Error: No tuner hardware found.\n";
        exit(1);        
    }        
        
    $action = @$_REQUEST["action"];        
    $tunerIndex = @$_REQUEST["tuner"];
    if (is_numeric($tunerIndex) && $tunerIndex >= 0 && $tunerIndex < count($atscAdapters)) {
        $tunerIndex = (int)$tunerIndex;
    } else {
        $tunerIndex = -1;
    }
    
    if ($action == "ReadLog") {        
        $jsonData = array();
        if ($tunerIndex < 0) {
                $jsonData['status'] = "ERROR";
        } else if (!scan_is_running($tunerIndex)) {    
            $jsonData['status'] = "NOSCAN";              
        } else {        
            $f = fopen(get_scan_log($tunerIndex), "r");
            if ($f) { 
                $log = "";
                while (!feof($f)) { 
                    $line = fgets($f);
                    $skip = FALSE != strpos($line, "(tuning failed)");
                    if (!$skip) 
                        $skip = "WARNING:" == substr($line, 0, strlen("WARNING:"));
                    if (!$skip)
                        $log .= utf8_encode($line);
                }
                $jsonData['data'] = $log;
                $jsonData['status'] = "OK";      
            } else {
                $jsonData['status'] = "ERROR";
            }
        }
        echo json_encode($jsonData);          
        exit();
    } else if ($action == "StartScan") { 
        $jsonData = array();
        if ($tunerIndex < 0) {
            $jsonData['status'] = "ERROR";
        } else if (scan_is_running($tunerIndex)) {    
            $jsonData['status'] = "SCANNING";              
        } else {
            $cmd = "echo \\\"".get_scan_cmd($tunerIndex)." 2>".get_scan_log($tunerIndex)." 1>".dvbapi_getChannelsConf($tunerIndex)." \\\" | at now";
            error_log("Executing $cmd");
            exec("sudo sh -c \"$cmd\"");        
            sleep(2);
            $jsonData['status'] = "OK";  
        }
        echo json_encode($jsonData);                  
        exit();
    } else if ($action == "GetChannels") {
        $jsonData = array();        
        if ($tunerIndex < 0) {
            $jsonData['status'] = "ERROR";        
        } else {
            $channels = dvbapi_parseChannelsConf(dvbapi_getChannelsConf($tunerIndex));    
            if (!$channels || !count($channels)) {
                $jsonData["channels"] = null;
                $jsonData['status'] = "OK";  
            } else {
                $jsonData["channels"] = dvbapi_sortChannelsByFreq($channels);                        
                $jsonData['status'] = "OK";  
            }
        }
        echo json_encode($jsonData);                  
        exit();        
    }
    
    $devices = array();
    for ($i = 0; $i < count($atscAdapters); $i += TUNERS_PER_CARD) {
        $devices[] = array(
            "index" => $i,
            "scan_is_running" => scan_is_running($i)
        );
    }
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Tuner Configuration</title>

    <link href="<?php echo filetimeUrl('css/smoothness/jquery-ui.css'); ?>" rel="stylesheet" type="text/css" />
    <link href="<?php echo filetimeUrl('css/styles.css'); ?>" rel="stylesheet" type="text/css" />
    <link href="<?php echo filetimeUrl('stylein.css'); ?>" rel="stylesheet" type="text/css" />
    <script src="<?php echo filetimeUrl('js/jquery.js'); ?>"></script>
    <script src="<?php echo filetimeUrl('js/jquery-ui.js'); ?>"></script>

    <script type="text/javascript" src="js/jquery.timers.js"></script>
    
    <script type="text/JavaScript">
        
    var devices = <?php echo json_encode($devices); ?>; 

    $(function() {        
        $("#tunerTabs").tabs();

        $(".scanButton").click(function() {
            performScan(2*$(".scanButton").index(this));
        });

        $.each(devices, function(i, device) {
            if (device.scan_is_running) {
                startPollingLog(device.index, true);
            }
        });
    });

    function readLog(deviceIndex)
    {
        $.getJSON("tuner.php", 
        { 
                action: "ReadLog",
                dt: new Date().getTime(),
                tuner: deviceIndex
        }, 
        function GetData(data) 
        {
            if(data.status == "OK")
            {
                var obj = document.getElementById("log_window"+deviceIndex);
                obj.value = data.data;
                obj.scrollTop = obj.scrollHeight;
            }
            else if (data.status == "NOSCAN")
            {   
                // Refresh page with scan results
                window.location.href = "tuner.php#tuner"+deviceIndex;
                window.location.reload();
            }
            else
            {
            }
        });
    }    

    var pollingLog = "4s";

    function startPollingLog(deviceIndex, start)
    {
        if(start)
        {
            readLog(deviceIndex);
            // Polling for reading the log
            $("#log_window"+deviceIndex).everyTime(pollingLog,"pollingLog"+deviceIndex, function() 
            {
                readLog(deviceIndex);                
            });
        }
        else
        {
            // Polling for reading the log
            $("#log_window"+deviceIndex).stopTime("pollingLog"+deviceIndex);
        }
    }
    
    function performScan(deviceIndex) {
        if (!confirm("Are you sure you want to scan for channels?  This will take a few minutes."))
            return;
            
        $.getJSON("tuner.php", 
            { action: "StartScan", dt: new Date().getTime(), tuner: deviceIndex },
            function (data) { 
                window.location.href = "tuner.php#tuner"+deviceIndex;
                window.location.reload();
            });
    }
    </script>
    
    <style>
    
    table { 
        border: 1px solid black;
        border-collapse: collapse;
        text-align: center;
    }

    th {
        background-color: #333;
        border-right: 1px solid black; 
        color: white;
        font-weight: bold;
    }

    td { text-align: left; border-right: }    
    .channel_numeric { text-align: right }    
    .channel_string {}
    .border_right { border-right: 1px solid black; }
    
    </style>
</head>

<body>
<div id="wrapper">
    <div id="banner"></div>
    <div id="nav">
        <ul id="sddm">
        </ul>
    </div>
    <div id="content1">
        <div id="box1">
            <h1 class="head">Tuner Configuration</h1>
            <div id="enq">
                <div class="errbox" align="center"></div>
                
                <div id="tunerTabs" style="font-size: 13px">
                    <ul>
                    <?php foreach ($devices as $device) { ?>
                        <li><a href="#tuner<?php echo $device["index"]; ?>">Tuner <?php echo $device["index"]+1; ?> - <?php echo $device["index"]+TUNERS_PER_CARD; ?><?php if ($device["scan_is_running"]) { echo " (Scanning...)"; } ?></a></li>
                    <?php } ?>
                    </ul>
                    <?php foreach ($devices as $device) { ?>
                    <div id="tuner<?php echo $device["index"];?>">
                    <?php 
                    if (!$device["scan_is_running"]) { 
                        $channels = dvbapi_parseChannelsConf(dvbapi_getChannelsConf($device["index"]));    
                        $byFreq = dvbapi_sortChannelsByFreq($channels);            
                        ?>
                        <p><button class="scanButton" style="height: 25px">Perform Channel Scan</button></p>
                        <?php if (count ($channels)) { ?>
                        <table cellspacing="0" cellpadding="6">
                            <tr>
                                <th>Frequency</th>
                                <th>Name</th>
                                <th>Mod</th>
                                <th>VID</th>
                                <th>AID</th>
                                <th>PID</th>
                            </tr>
                            <?php 
                                foreach ($byFreq as $freq => $channelsByFreq)
                                {   
                                    $first = true;
                                    foreach ($channelsByFreq as $channel)
                                    {
                                        $freqDisplay = $first ? "{$channel->freq} Hz" : "";
                                        $topBorder = $first ? "style='border-top: 1px solid black'" : "";
                                        echo "<tr>";
                                        echo "<td class='border_right' $topBorder><b>{$freqDisplay}</b></td>";
                                        echo "<td $topBorder class='channel_string border_right'>{$channel->name}</td>";
                                        echo "<td $topBorder class='channel_string border_right'>{$channel->mod}</td>";
                                        echo "<td $topBorder class='channel_numeric border_right'>{$channel->vid}</td>";
                                        echo "<td $topBorder class='channel_numeric border_right'>{$channel->aid}</td>";
                                        echo "<td $topBorder class='channel_numeric'>{$channel->pid}</td>";                                    
                                        echo"</tr>\n";
                                        $first = false;
                                    }
                                }
                            ?>                    
                        </table>                  
                        <?php } else { ?>
                        <p>No channels available.  Please perform scan.</p>
                        <?php } ?>
                    <?php } else { ?>
                    <h2>Scan is in progress...</h2> 
                    <textarea id="log_window<?php echo $device["index"];?>" rows="25" cols="100" readonly="true" style="width:700px" onfocus="startPollingLog(<?php echo $device["index"]; ?>, false);" onblur="startPollingLog(<?php echo $device["index"]; ?>, true);">
                    </textarea>                                    
                    <?php } ?>
                    </div>
                <?php } ?>
                </div>
            </div>
        </div>
    </div>
</div>

</body>
</html>
