Core/CakeBuild-Module.psm1

$ErrorActionPreference = "Stop"

function GetCacheFileFullPath {
    [CmdletBinding()]
    Param
    (
        [string]$RootDirectory
    )

    $cacheDir = "$RootDirectory\_saf\cache"
    if (!(Test-Path "$cacheDir")){ 
        New-Item -Path "$cacheDir" -Type Directory -Force | Out-Null
    }

    $cacheFile = "$cacheDir\cache.txt"
    return $cacheFile
}

function InitializeCakeBuild {
    [CmdletBinding()]
    Param
    (
        [string]$CakeBuildFile
    )

    $setupDir = Split-Path "$CakeBuildFile"
    Copy-Item -Path "$PSScriptRoot\Templates\build.ps1" -Destination "$setupDir" -Force | Out-Null
    & "$setupDir\build.ps1" -Script "$CakeBuildFile" --settings_skippackageversioncheck=true --settings_skipverification=true
}

function GetCakeBuildFilePath {
    [CmdletBinding()]
    Param
    (
        [string]$CurrentDirectory
    )

    $vsDir = FindParentDirectory -CurrentDirectory $CurrentDirectory -Search ".vs"
    $safRootDir = Split-Path "$vsDir"
    $cacheFile = GetCacheFileFullPath -RootDirectory "$safRootDir"
    if (!(Test-Path $cacheFile)) {
        return $null
    }

    foreach ($line in Get-Content $cacheFile) {
        if ($line.StartsWith("CakeBuildFile")) {
            return $line.Split('=')[1]
        }
    }
    
    return $null
}

function SaveCakeBuildFilePath {
    [CmdletBinding()]
    Param
    (
        [string]$CakeBuildFile
    )

    $CakeBuildFile = $CakeBuildFile.Replace("build.cake", "build.ps1")
    $setupDir = Split-Path "$CakeBuildFile"
    $vsDir = FindParentDirectory -CurrentDirectory $setupDir -Search ".vs"
    $safRootDir = Split-Path "$vsDir"
    $cacheFile = GetCacheFileFullPath -RootDirectory "$safRootDir"
    New-Item $cacheFile -ItemType File -Force | Out-Null

    $cacheValue = "CakeBuildFile=$CakeBuildFile"
    Add-Content -Path $cacheFile -Value $cacheValue -Encoding "UTF8" -Force | Out-Null
}

function GetCakeBuildStringProperty {
    [CmdletBinding()]
    Param
    (
        [string]$CakeFile,
        [string]$PropertyName
    )

    foreach ($line in Get-Content "$CakeFile") {
        if ($line.Contains(" $PropertyName ")) {
            $startIndex = $line.IndexOf("`"")
            $endIndex = $line.LastIndexOf("`"")
            return $line.Substring($startIndex + 1, $endIndex - $startIndex  - 1)
        }
    }

    return ""
}

Export-ModuleMember -Function "InitializeCakeBuild"
Export-ModuleMember -Function "GetCakeBuildFilePath"
Export-ModuleMember -Function "SaveCakeBuildFilePath"
Export-ModuleMember -Function "GetCakeBuildStringProperty"