#encoding:utf8
$cur_dir = Split-Path $MyInvocation.MyCommand.Path
$dir_main = "$cur_dir/../"
$dir_erl = $dir_main
$dir_log = "$dir_erl/logs"
$werl = "werl"
$erl = "erl"
$param_pa = "-pa " + $($dir_erl -replace "\\", "/") + "/ebin" 

function fun_make(){
    $src = $dir_main + "/src"
    $inc = $dir_main + "/include"
    $timefile = $cur_dir + "/timefile"
    #$beamfile = $dir_main + "/ebin"
    $lastTime = $(Get-Item $timefile).LastWriteTime
    #$beamTime = $(Get-Item $beamfile).LastWriteTime
    #$measureObject = $lastTime, $beamTime | Measure-Object -Maximum
    #$latestTime = $measureObject.Maximum
    $latestTime = $lastTime
    function get_hrl_str(){
        begin{ $list = @() }
        process{ $list += $_.Name }
        end{
            $str = $list -join "|"
            if($str -ne ""){
                $str = "($str)"
            }
            $str
        }
    }
    $chhrl_str = Get-ChildItem $inc -Include *.hrl -Recurse | Where-Object {$_.LastWriteTime -gt $latestTime} | get_hrl_str

    ## 使用管道获取变化的文件
    ## 1. 获取所有文件
    ## 2. 检测变化文件
    ## 3. 生成文件全名列表
    function get_erl_str(){
        begin{ $list = @() }
        process{
            $f = $_.FullName -replace "\\", "/"
            $list += "`\`"$f`\`""
        }
        end{ $list -join "," }
    }
    $erl_str = Get-ChildItem $src -Include *.erl -Exclude .svn,.git -Recurse | Where-Object {
        if ( $(Get-Item $_.FullName).LastWriteTime -gt $latestTime ){
            return $_
        }
        if($chhrl_str -eq ""){
            return $false
        } 
        if (Select-String -Path $_.FullName -Pattern $chhrl_str -Quiet) {
            return $_
        }else{
            return $false
        }
    } | get_erl_str
    
    Set-Location $dir_erl
    ## 在windows下
    ## 直接mmake:files(5, [])无效
    ## 必须mmake:files(5, [], Opts)
    ## why? {{ok,[{{_, Opts}}|_]}}
    $cmd_str = '{0} {1} -noshell -eval "{{ok,FileInfo}}=file:consult(\"./Emakefile\"),{{_, Opts}}=lists:last(FileInfo),case mmake:files(5,[{2}], Opts) of up_to_date -> init:stop(); _ -> init:stop(1) end"'

    $cmd = $cmd_str -f $erl, $param_pa, $erl_str
    ## echo $cmd
    cmd /C $cmd
    if ($?) {
        Write-Output "=============> success"
        (Get-Date).ToString() | Out-File $timefile -Append
    }else{
        Write-Error "==============> fail"
    }
    Set-Location $cur_dir
}

fun_make

