<?php

date_default_timezone_set('America/New_York');
header("Content-Type: text/plain");

$id = $_GET['id'];
$eventId = $_GET['eventId'];
$mediaId = $_GET['mediaId'];
$time = $_GET['time'];
$direcctorio = "/var/www/html/star/channels/" . $id;

$server = 'https://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
$path_video = str_replace ("master_co.php" , 'video_f.php/' , $server);
$path_audio = str_replace ("master_co.php" , 'audio_f.php/' , $server);
$path = str_replace ('master_co.php' , '' , $server);
                           
$info = file_get_contents("http://localhost/star/ec.php?id=" . $id."&eventId=".$eventId."&mediaId=".$mediaId."&time=".urlencode($time));
$info2 = file_get_contents("http://localhost/star/br.php?id=" . $id."&eventId=".$eventId."&mediaId=".$mediaId."&time=".urlencode($time));
$json = json_decode($info, true);
$json2 = json_decode($info2, true);

$key = !empty($json['Key']) ? $json['Key'] : $json2['Key'];
$url = $json['url'];
$master = explode('ctr', $url);
if ($key !== 'null') {
    mkdir($direcctorio, 0777, true);
    $cierto = file_get_contents($direcctorio . '/' . $id . '.key');
    if (!file_exists($direcctorio . '/' . $id . '.key') or $cierto == 'null' or empty($cierto)) {
        echo 'Generating Event...' . chr(10);
        file_put_contents($direcctorio . '/' . $id . '.key', $key);
        file_put_contents($direcctorio . '/' . $id . '.url', $master[0]);
        
$contenido = '#EXTM3U
#EXT-X-INDEPENDENT-SEGMENTS
#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="aac-128k",NAME="Português (Brasil)",LANGUAGE="pt-BR",DEFAULT=YES,AUTOSELECT=YES,CHANNELS="2",URI="'.$path_audio. $id . '/audio-1-128K/128_slide.m3u8"
#EXT-X-STREAM-INF:BANDWIDTH=8397000,AVERAGE-BANDWIDTH=6926000,CODECS="avc1.640020,mp4a.40.2",RESOLUTION=1080x720,FRAME-RATE=59.94,HDCP-LEVEL="TYPE-0",CHARACTERISTICS="com.dss.ctr.hd",AUDIO="aac-128k",CLOSED-CAPTIONS=NONE'.PHP_EOL.$path_video . $id . '/cmaf-cenc-ctr-7000K/7000_slide.m3u8';

        file_put_contents($direcctorio . '/index.m3u8', $contenido);
    } else {
	
header('Content-type:application/x-mpegURL');
echo '#EXTM3U
#EXT-X-INDEPENDENT-SEGMENTS
#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="aac-128k",NAME="Português (Brasil)",LANGUAGE="pt-BR",DEFAULT=YES,AUTOSELECT=YES,CHANNELS="2",URI="'.$path_audio. $id . '/audio-1-128K/128_slide.m3u8"
#EXT-X-STREAM-INF:BANDWIDTH=8397000,AVERAGE-BANDWIDTH=6926000,CODECS="avc1.640020,mp4a.40.2",RESOLUTION=1080x720,FRAME-RATE=59.94,HDCP-LEVEL="TYPE-0",CHARACTERISTICS="com.dss.ctr.hd",AUDIO="aac-128k",CLOSED-CAPTIONS=NONE'.PHP_EOL.$path_video . $id . '/cmaf-cenc-ctr-7000K/7000_slide.m3u8';

    }
} else {
    echo 'Not Available';
}

