<?php
#ini_set('display_errors', 0);
#int error_reporting ([ int $レベル ] )
#error_reporting ( ~E_ALL );
#error_reporting ( ~E_ERROR );

$settings_yml_path = "/../settings-devconf.yml";

header("Access-Control-Allow-Origin: *");
#namespace ns;

require_once( dirname(__FILE__) . '/func.php');
require_once( dirname(__FILE__) . '/NorthernCross/ns/PathItem.php');
require_once( dirname(__FILE__) . '/NorthernCross/ns/PathInfo.php');
require_once( dirname(__FILE__) . "/spyc-0.5/spyc.php"); // ★の部分にはspyc.phpを置いたパスを入れます

$exec_path = dirname(__FILE__) . "/..";

function get_url_data_array()
{
    global $settings_yml_path;

    $yaml= spyc_load_file( dirname(__FILE__) . $settings_yml_path);// ☆の部分にはyamlファイルがあるパスを入れます
    return $yaml;
}

function get_url_data_array0()
{
	$array = array(
        array('url' => 'https://toppers.jp', 'path' =>	'/var/www/vhosts/devconf.northern-cross.info/httpdocs/a/tmp/devconf-guest-4/tmp/md2site-x/_xtest/wtjx/t12/src') );

	return $array;
}

function get_url_data( $num ){
    $array = get_url_data_array();
    return $array[$num];
}

function dump_url_data( $num ){
    print_r( get_url_data( $num ));	 
}

function get_path_from_url_data( $num , $part){
    switch($part){
    case 'data':
        $ret = get_url_data( $num )['path'];
        break;
    case 'conf':
        $ret = get_url_data( $num )['conf_path'];
        break;
    case 'output':
        $ret = get_url_data( $num )['output_path'];
        break;
    default:
        //exit(200);
        echo "get_path_from_url_data " . $part . "<br>";
    }

    return $ret;
}

function get_path_list_by_url( $num , $part){
    $top_path = get_path_from_url_data($num, $part);

    switch($part){
    case 'data':
#        $pattern = "*.md";
        $regexp = '".*\(md\|yml\)"';
#        $regexp = '".*\(yml\)"';
 #       $cmd_line_items = array("find" , $top_path , "-name", $pattern);
        $cmd_line_items = array("find" , $top_path , "-regex", $regexp);
        break;
    case 'conf':
        $regexp = '".*[^~]"';
        $cmd_line_items = array("find" , $top_path , "-type", "f", "-regex" , $regexp);
        break;
    case 'output':
        $regexp = '".*htm[^~]"';
        $cmd_line_items = array("find" , $top_path , "-type", "f", "-regex" , $regexp);
        break;
    default:
        echo "get_path_list_by_url=" . $part . "<br>";
        exit(100);
    }
    $cmd_line = implode(" " , $cmd_line_items);

    $array = array();
    $handle = popen( $cmd_line , "r");
    while (( $buffer = fgets($handle, 4096)) !== false){
        $line = trim($buffer);
        $data = explode($top_path,  $line)[1];
        array_push($array , $data);
    }
    if (!feof($handle)) {
	    echo "Error: unexpected fgets() fail\n";
    }
    pclose($handle);
    
    return array( "top_path" => $top_path, "file_list" => $array);
}

function restrict_filelist( $num, $path_info , $part ) {
    if( $part === "conf" ){
        $pathinfox = new ns\PathInfo($part, $path_info["top_path"]);
    }
    else{
        $output_htmls = get_restrict_basenames( $num );
        $pathinfox = new ns\PathInfo($part, $path_info["top_path"] , $output_htmls);

        foreach($path_info["file_list"] as $path){
            $pathinfox->scan($path);
        }
    }

    foreach($path_info["file_list"] as $path){
        $pathinfox->register($path);
    }

    return $pathinfox->pathinfo_list_in_json();
}


function get_path_info( $num , $part){
    $path_info = get_path_list_by_url( $num , $part);

    return restrict_filelist( $num, $path_info , $part);
 }

function ensure_dir( $dir ) {
    if( !file_exists( $dir ) ){
        mkdir( $dir );
    }
}

function ensure_storage_dir( $storage_dir , $num, $filename ) {
    $dir = implode( "/" , array( $storage_dir , $num) );
    mkdir($dir);
    $path = implode( "/" , array( $dir , $filename) );
#    echo "path=$path";
    ensure_dir( $dir );

    return $path;
}

function get_content( $num , $path , $part) {
    $top_dir = get_path_from_url_data( $num , $part);
    $full_path = implode( '/', [$top_dir, $path]);
    $result = input_file( $full_path );
    return $result;
}

function build_one_html( $exec_path, $num , $md_path , $part) {
    $pathinfo = pathinfo( $md_path );
    $md_fname = $pathinfo['basename'];
    
    $base = $pathinfo['filename'];

    $list = get_site_tsv( $num );

    debug_vd( $list );

    $t = $list[$base]["t"];
    $s = $list[$base]["s"];
    $output_html = $list[$base]["output_html"];

    $url_data = get_url_data( $num );
    $bundle_path = $url_data["bundle_path"];
    $conf_path = $url_data["conf_path"];
    $output_url = $url_data["output_url"];

    $cmd_line_items = array( $exec_path . "/bin/build.sh" , $bundle_path , $t, $s, $conf_path);

    $cmd_line = implode(" " , $cmd_line_items);

    $array = array();
    $handle = popen( $cmd_line , "r");

    while (( $buffer = fgets($handle, 4096)) !== false){
        $line = trim($buffer);
        array_push($array , $line);
    }
    if (!feof($handle)) {
	    echo "Error: unexpected fgets() fail\n";
    }
    pclose($handle);

    $full_download_url = implode( "/" , array( $output_url , $output_html ) );

    $html_fname_tmp = $output_html  . ".tmp";
    $partial_download_url = implode( "/" , array( $output_url , $html_fname_tmp) );

    $info = array( "full_download_url" => $full_download_url,
                   "partial_download_url" => $partial_download_url );

    return $info;
}

function cmdx(){
    global $exec_path;

    $filelist_filename = array("data"=> "filelist.json", "conf"=> "conf-filelist.json", "output" => "output-filelist.json");
    #    $storage_dir = dirname(__FILE__) . '/../storage';
    $storage_dir = dirname(__FILE__) . '/../storage-devconf';

    $content = NULL;
    if (isset($_GET['cmd'])) {
        $cmd = $_GET['cmd'];
        if (isset($_GET['num'])) {
            $num = $_GET['num'];
            if (isset($_GET['part'])) {
                $part = $_GET['part'];

                switch ($cmd) {
                case 'get_content':
                    if (isset($_GET['path'])) {
                        $path = $_GET['path'];
                        $content = get_content( $num , $path , $part );
                    }
                    break;
                case 'update_filelistx':
                    $path = ensure_storage_dir( $storage_dir , $num, $filelist_filename[$part] );
                    $content = get_path_info( $num , $part);
                    output_file( $path , $content );
                    break;
                case 'get_filelistx':
                    $path = ensure_storage_dir( $storage_dir , $num, $filelist_filename[$part] );
                    if( file_exists($path) ){
                        $content = input_file( $path );
                    }
                    else {
                        $content = get_path_info( $num , $part);
                        output_file( $path , $content );
                    }
                    break;
                default:
                    break;
                }
            }
            else{
                switch ($cmd) {
                case 'get_output_url':
                    $info = array('output_url' => get_output_url($num));
                    $content = json_encode($info);
                    break;
                default:
                    break;
                }
            }
        }
    }

    elseif (isset($_POST['cmd'])) {
        $cmd = $_POST['cmd'];
        if (isset($_POST['num'])) {
            $num = $_POST['num'];
            if (isset($_POST['part'])) {
                $part = $_POST['part'];

                switch ($cmd) {
                case 'build_one_html':
                    $array = get_lines_from_formdata( "mytext" );
                    $upload_content = implode( "\n" , $array );
                    if (isset($_POST['path'])) {
                        $path = $_POST['path'];
                        $top_path = get_path_from_url_data( $num , $part);
                        $filename_abs_path = $top_path . DIRECTORY_SEPARATOR . $path;
                        $ret = build_one_html( $exec_path , $num, $path, $part );
                    }
                    else{
                        output_file( dirname(__FILE__) . "/debug-F.txt" , "ABCDEFG" );
                        $ret = "P-UPLOAD_CONTENT-NO-PATH";
                    }
                    $content = json_encode( $ret );
                    break;
                case 'upload_content':
                    $array = get_lines_from_formdata( "mytext" );
                    $upload_content = implode( "\n" , $array );
                    if (isset($_POST['path'])) {
                        $path = $_POST['path'];
                        $top_path = get_path_from_url_data( $num , $part);
                        $filename_abs_path = $top_path . DIRECTORY_SEPARATOR . $path;
                        
                        output_file( $filename_abs_path , $upload_content );
                        $content = $upload_content;
                    }
                    else{
                        $content = json_encode("P-UPLOAD_CONTENT-NO-PATH");
                    }
                    
                default:
                    debug_x("P-DEFAULT");
                    /* $content = "P-DEFAULT";*/
                    break;
                }
            }
        }
        else{
            $content = json_encode("P-NO_NUM");
#            $content = json_encode("{pxyz:123}");
        }
    }
    else{
        debug_x('DEFAULT');
    }

    if(!is_null($content)){
#        $content = "PABCEDFG";
        echo($content);
#        debug_x("CONTENT");
    }
    else{
        echo($content);
    }
}

function debug_x($mes, $fname = null) {
    ob_start();
    echo $mes . "\n";
    /*    var_dump($_GET);*/
    /*    var_dump($_POST);*/
    ob_end_clean();
    $contentx = ob_get_contents();
    if( $fname === null ){
        $fname = './debug.txt';
    }

    error_log($contentx, 3, $fname );
}

function debug_vd($var) {
    ob_start();
    var_dump( $var );
    ob_end_clean();
    $content = ob_get_contents();
    output_file( "debug.txt" , $content );
}

function get_full_path($num, $key, $fname){
    $array = get_url_data_array();
    return $array[$num][$key] . "/" . $fname;
}

function get_restrict_from_settings_yml() {
    $settings = get_url_data_array();
    $array = $settings[0]['restrict'];

    $r_keys = array_keys( $array );
    $restrict_array = array();
    foreach( $array as $k => $v ){
        $restrict_array[$k] = array();
        foreach( $v as $k2 => $v2 ){
            $restrict_array[$k][$k2] = array();
            foreach( $v2 as $k3 => $v3 ){
                foreach( $v3 as $k4 => $v4 ){
                    $restrict_array[$k][$k2][$v4] = "";
                }
            }
        }
    }

    return $restrict_array;
}

function get_restrict_basenames( $num ) {
    $output_htmls = array();

    $list = get_site_tsv($num );

    $restrict_array = get_restrict_from_settings_yml();

    foreach( $list as $k => $v ){
        if( isset( $restrict_array[ $v['category'] ][ $v['t'] ][ $v['s'] ] ) ) {
            $output_htmls[$k] = $v['output_html'];
        }
    }

    return $output_htmls;
}

function get_site_tsv($num){
    $list = array();

    $fname = get_full_path( $num, 'conf_path' , 'site.tsv');
    if (($f = fopen( $fname , "r" )) !== FALSE) {
        while (($data = fgetcsv($f, 1000, "\t")) !== FALSE) {
            if( !preg_match("/^#/" , $data[0]) ){
                $t = $data[0];
                $s = $data[1];
                $category = $data[2];
                $output_html = $data[3];
                if( count($data) > 4 ){
                    $alias_html = $data[4];
                }
                else{
                    $alias_html = "";
                }
                $basename = basename( $output_html , ".html");
                $list[$basename] = array( 't'=> $t, 's'=> $s, 'category'=>$category, 'output_html' => $output_html, 'alias_html'=> $alias_html );
            }
        }
        fclose($f);
    }

    return $list;
}

function get_output_url($num){
    $settings = get_url_data_array();
    return $settings[$num]['output_url'];
}

function get_restrict($num){
    $settings = get_url_data_array();
    return $settings[$num]['restrict'];
}

function get_item($num, $name){
    $settings = get_url_data_array();
    return $settings[$num][$name];
}

function get_settings_file( $name ){
    $dir = get_item( 0 , "conf_path" );
    $path = implode( "/" , [$dir, $name] );

    return $path;
}

cmdx();
/*
$num = 0;
$path = "/attempt/devconf2018/data/devconf2018.md";
$part = "data";
$lines = build_one_html( $exec_path, $num , $path , $part );

var_dump( $lines );

foreach( $lines as $k => $v ){
    if( is_array( $v )){
        echo implode( "\n" , $v );
    }
    else{
        echo $v . "\n";
    }
}
*/
?>
