. $PSScriptRoot\_echo.ps1
. $PSScriptRoot\criptografiaSenha.ps1


function global:mu.muDllRest.pararEExcluirServico {
    cmd /c sc stop MuDllRest
    cmd /c sc delete MuDllRest
}

function global:mu.muDllRest.configurarDadosDeAcessoAoBanco {
    param(
        $configuracoes
    )

    $appSettingsJsonDestino = "$($configuracoes.enderecos.diretorioBaseInstalacao)\MuDllRest\publish\appSettings.json"
    
    $hostEscapado = $configuracoes.acessos.banco.host -replace '\\','\\'

    (Get-Content -Path $appSettingsJsonDestino -Raw) -replace '\$PORTA',"$($configuracoes.muDllRest.porta)" | Set-Content -Path $appSettingsJsonDestino
    (Get-Content -Path $appSettingsJsonDestino -Raw) -replace '\$DB_HOST',"$hostEscapado" | Set-Content -Path $appSettingsJsonDestino
    (Get-Content -Path $appSettingsJsonDestino -Raw) -replace '\$DB_NAME',"$($configuracoes.acessos.banco.nomeBanco)" | Set-Content -Path $appSettingsJsonDestino
    
    $senhaBancoCriptograda = $configuracoes.acessos.banco.senha
    $senhaBancoDescriptografada = mu.descriptografarSenha $senhaBancoCriptograda
    (Get-Content -Path $appSettingsJsonDestino -Raw) -replace '\$DB_PASSWORD',$senhaBancoDescriptografada | Set-Content -Path $appSettingsJsonDestino
    (Get-Content -Path $appSettingsJsonDestino -Raw) -replace '\$DB_USER',"$($configuracoes.acessos.banco.usuario)" | Set-Content -Path $appSettingsJsonDestino
}

function global:mu.muDllRest.configurarDadosDeAcessoAoBanco.test {
    . $PSScriptRoot\.\configuracoesMicrouniversoWeb.ps1

    $enderecoArquivoConfiguracao = "C:\microuniversoWeb\microuniversoWeb.yaml"
    $configuracoes = mu.configuracoesMicrouniversoWeb.obter $enderecoArquivoConfiguracao

    mu.muDllRest.configurarDadosDeAcessoAoBanco $configuracoes
}

function global:mu.muDllRest.configurarESubirServico {
    param(
        $configuracoes
    )

    $exePath = "$($configuracoes.enderecos.diretorioBaseInstalacao)\MuDllRest\publish\MuDllRest.exe"
    $usuario = $configuracoes.acessos.usuarioAdministrador.usuario
    $senha = $configuracoes.acessos.usuarioAdministrador.senha

    cmd /c sc create MuDllRest binPath= "$exePath" start= auto

    # cmd /c sc.exe config MuDllRest obj= ".\$usuario" password= "$senha"

    cmd /c sc start MuDllRest
}

function global:mu.muDllRest.configurarESubirServico.test {
    . $PSScriptRoot\.\configuracoesMicrouniversoWeb.ps1

    $enderecoArquivoConfiguracao = "C:\microuniversoWeb\microuniversoWeb-enterprise.yaml"
    $configuracoes = mu.configuracoesMicrouniversoWeb.obter $enderecoArquivoConfiguracao

    mu.muDllRest.configurarESubirServico $configuracoes
}

function global:mu.muDllRest.garantirQueDllInscE32EstaInstalada() {

    param(
        $configuracoes
    )

    $dllNoSyswow64 = "c:\windows\syswow64\DllInscE32.dll"
    $dllNoRelease = "$($configuracoes.enderecos.diretorioBaseInstalacao)\MuDllRest\DllInscE32.dll"

    if (test-path $dllNoSyswow64) {
        _echo "DllInscE32.dll ja esta instalada em $dllNoSyswow64"
        return
    }

    if (-not (test-path $dllNoRelease)) {
        throw "DllInscE32.dll nao encontrada em $dllNoRelease"
    }

    _echo "Copiando $dllNoRelease para $dllNoSyswow64"
    copy-item $dllNoRelease $dllNoSyswow64

}







function global:mu.muDllRest.clonarMuDllRestRelease () {
    param(
        $configuracoes
    )

    $usuario = $configuracoes.muDllRest.git.usuario
    $senha = $configuracoes.muDllRest.git.senha
    $tag = $configuracoes.muDllRest.versao

    $url = "https://${usuario}:${senha}@gitlab.microuniverso.com.br/Microuniverso/MUFenix/MuDllRestRelease.git"
    $diretorioMuDllRestRelease = "$($configuracoes.enderecos.diretorioBaseInstalacao)\MuDllRest"

    $_ErrorActionPreference = $ErrorActionPreference
    $ErrorActionPreference = 'Continue'

    if (Test-Path -Path $diretorioMuDllRestRelease) {
        Remove-Item -Path $diretorioMuDllRestRelease -Force -Recurse
    }

    
    git clone $url $diretorioMuDllRestRelease | Out-Null

    if ($tag.ToLower() -ne 'master') {
        Push-Location $diretorioMuDllRestRelease
        git checkout tags/$tag | Out-Null
        Pop-Location
    }

    $ErrorActionPreference = $_ErrorActionPreference


}

function global:mu.muDllRest.configurarMuDllRest {
    param(
        $configuracoes,
        $enderecoArquivoConfiguracao,
        $diretorioScriptsImplantacao
    )

    if ($configuracoes.muDllRest.configurar -eq $false) {
        _echo "MuDllRest desativado via configuracao" warn
        return
    }

    _echo "Configurando MuDllRest"

    _echo "MuDllRest - Parando e excluindo servico"
    mu.muDllRest.pararEExcluirServico

    _echo "Atualizando srvcusto"

    $exitCode = mu.executarScriptPython -script "$psscriptroot\scriptsPython\configurar_srvcusto.py" -argumentos "$enderecoArquivoConfiguracao $diretorioScriptsImplantacao"

    if ($exitCode -ne 0) {
        throw "erro ao configurar srvcusto para mudllrest"
    }

    _echo "MuDllRest - Clonando MuDllRestRelease"
    mu.muDllRest.clonarMuDllRestRelease $configuracoes

    

    _echo "Garantindo que DllInscE32.dll esta instalada"
    mu.muDllRest.garantirQueDllInscE32EstaInstalada $configuracoes

    _echo "MuDllRest - Configurando dados de acesso ao banco"
    mu.muDllRest.configurarDadosDeAcessoAoBanco $configuracoes

    _echo "MuDllRest - Configurando e iniciando servico"
    mu.muDllRest.configurarESubirServico $configuracoes
}

function global:mu.muDllRest.configurarMuDllRest.test {
    . $PSScriptRoot\.\configuracoesMicrouniversoWeb.ps1

    $enderecoArquivoConfiguracao = "C:\TrabalhoWeb\ScriptsDeploy\scripts_implantacao\arquivos-yml-teste\microuniversoWeb-MuDllRest.yaml"
    $configuracoes = mu.configuracoesMicrouniversoWeb.obter $enderecoArquivoConfiguracao
    

    mu.muDllRest.configurarMuDllRest $configuracoes 
}
