# syntax=docker/dockerfile:1
# escape=`
ARG BUILD_BASE_IMAGE=mcr.microsoft.com/windows/servercore:ltsc2022
FROM $BUILD_BASE_IMAGE as builder_base

ARG PCRE2_VERSION=10.39
ARG OPENSSL_VERSION=3.0.8
ARG GOLANG_VERSION=1.19.6
ARG SEVEN_ZIP_VERSION=2107
ARG BUILD_ARCH=x64
ARG CPU_MODEL=AMD64

ARG MAJOR_VERSION=6.4
ARG ZBX_VERSION=${MAJOR_VERSION}

ARG VS_BUILDTOOLS_URL=https://aka.ms/vs/16/release/vs_buildtools.exe
ARG GIT_URL=https://github.com/git-for-windows/git/releases/download/v2.33.0.windows.2/MinGit-2.33.0.2-busybox-64-bit.zip
ARG MINGW_URL=https://sourceforge.net/projects/mingw-w64/files/Toolchains%20targetting%20Win64/Personal%20Builds/mingw-builds/8.1.0/threads-win32/sjlj/x86_64-8.1.0-release-win32-sjlj-rt_v6-rev0.7z
ARG GOLANG_URL=https://golang.org/dl/go$GOLANG_VERSION.windows-amd64.msi
ARG CYGWIN_URL=https://cygwin.com/setup-x86_64.exe
ARG PCRE2_URL=https://github.com/PhilipHazel/pcre2/releases/download/pcre2-$PCRE2_VERSION/pcre2-$PCRE2_VERSION.zip
ARG OPENSSL_URL=https://www.openssl.org/source/openssl-$OPENSSL_VERSION.tar.gz
ARG SEVEN_ZIP_URL=https://www.7-zip.org/a/7z$SEVEN_ZIP_VERSION-$BUILD_ARCH.msi

ENV ZBX_VERSION=$ZBX_VERSION `
    BUILD_ARCH=$BUILD_ARCH CPU_MODEL=$CPU_MODEL `
    PCRE2_VERSION=$PCRE2_VERSION OPENSSL_VERSION=$OPENSSL_VERSION `
    GOLANG_VERSION=$GOLANG_VERSION SEVEN_ZIP_VERSION=$SEVEN_ZIP_VERSION `
    GIT_URL=$GIT_URL MINGW_URL=$MINGW_URL CYGWIN_URL=$CYGWIN_URL GOLANG_URL=$GOLANG_URL SEVEN_ZIP_URL=$SEVEN_ZIP_URL `
    PCRE2_URL=$PCRE2_URL OPENSSL_URL=$OPENSSL_URL

LABEL org.opencontainers.image.title="Zabbix agent 2 build base for Windows" `
      org.opencontainers.image.authors="Alexey Pustovalov <alexey.pustovalov@zabbix.com>" `
      org.opencontainers.image.vendor="Zabbix LLC" `
      org.opencontainers.image.url="https://zabbix.com/" `
      org.opencontainers.image.description="Zabbix build base image contains all required packages to build Zabbix agent 2 images" `
      org.opencontainers.image.licenses="GPL v2.0" `
      org.opencontainers.image.documentation="https://www.zabbix.com/documentation/${MAJOR_VERSION}/manual/installation/containers" `
      org.opencontainers.image.version="${ZBX_VERSION}"

SHELL ["powershell", "-Command", "$ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue';"]

RUN Set-Location -Path $env:SystemDrive\.; `
    `
    Write-Host ('Downloading {0} ...' -f $env:GIT_URL); `
    [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; `
    Invoke-WebRequest -OutFile $env:SystemDrive\git.zip -Uri $env:GIT_URL; `
    `
    $sha256 = '273f55e881094d00877d64f56570b0c997c4da5dedcb26738d56481033c1eba1'; `
    Write-Host ('Verifying SHA256 ({0}) ...' -f $sha256); `
    if ((Get-FileHash $env:SystemDrive\git.zip -Algorithm sha256).Hash -ne $sha256) { `
        Write-Host 'Checksum GIT for Windows failed!'; `
        exit 1; `
    }; `
    `
    Write-Host 'Installing ...'; `
    Expand-Archive -Path git.zip -DestinationPath $env:SystemDrive\git\.; `
    Write-Host 'Removing downloaded...'; `
    Remove-Item -Force -Path $env:SystemDrive\git.zip; `
    $env:PATH = [string]::Format('{0}\git\cmd;{0}\git\mingw64\bin;{0}\git\usr\bin;', $env:SystemDrive) + $env:PATH; `
    [Environment]::SetEnvironmentVariable('PATH', $env:PATH, [EnvironmentVariableTarget]::Machine); `
    `
    Write-Host 'Verifying install ("git version") ...'; `
    git version; `
    `
    Write-Host ('Downloading {0} ...' -f $env:GOLANG_URL); `
    [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; `
    Invoke-WebRequest -OutFile $env:SystemDrive\go-amd64.msi -Uri $env:GOLANG_URL; `
    $sha256 = '205c178f7ebe29fa24fac72ddc097d3a37f541f93eae0ccf84d61cc459dc76d0'; `
    `
    Write-Host ('Verifying SHA256 ({0}) ...' -f $sha256); `
    if ((Get-FileHash $env:SystemDrive\go-amd64.msi -Algorithm sha256).Hash -ne $sha256) { `
        Write-Host 'Checksum Go Lang failed!'; `
        exit 1; `
    }; `
    Write-Host 'Installing ...'; `
    Start-Process `
        -FilePath $env:SystemDrive\go-amd64.msi `
        -Wait `
        -ArgumentList '/qn /norestart'; `
    Write-Host 'Removing downloaded...'; `
    Remove-Item -Force -Path $env:SystemDrive\go-amd64.msi; `
    `
    $env:PATH = [string]::Format('{0}\Go\bin;', ${env:ProgramFiles}) + $env:PATH; `
    [Environment]::SetEnvironmentVariable('PATH', $env:PATH, [EnvironmentVariableTarget]::Machine); `
    Write-Host 'Verifying install ("go version") ...'; `
    go version; `
    `
    Write-Host ('Downloading {0} ...' -f $env:SEVEN_ZIP_URL); `
    [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; `
    Invoke-WebRequest -OutFile $env:SystemDrive\7z.msi -Uri $env:SEVEN_ZIP_URL; `
    `
    $sha256 = '5447C9AC39C48F1BC7C88359B0520396A8C9707B307C107236A93A68E6FD3EB6'; `
    Write-Host ('Verifying SHA256 ({0}) ...' -f $sha256); `
    if ((Get-FileHash $env:SystemDrive\7z.msi -Algorithm sha256).Hash -ne $sha256) { `
        Write-Host 'Checksum 7-zip failed!'; `
        exit 1; `
    }; `
    `
    Write-Host 'Installing ...'; `
    Start-Process `
        -FilePath $env:SystemDrive\7z.msi `
        -Wait `
        -ArgumentList '/qn /norestart'; `
    Write-Host 'Removing downloaded...'; `
    Remove-Item -Force -Path $env:SystemDrive\7z.msi; `
    $env:PATH = [string]::Format('{0}\7-Zip;', ${env:ProgramFiles}) + $env:PATH; `
    [Environment]::SetEnvironmentVariable('PATH', $env:PATH, [EnvironmentVariableTarget]::Machine); `
    `
    Write-Host 'Verifying install ("7z -h") ...'; `
    7z -h | Select -first 2; `
    `
    Write-Host ('Downloading {0} ...' -f $env:MINGW_URL); `
    [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; `
    (new-object System.Net.WebClient).DownloadFile("""$env:MINGW_URL""","""$env:SystemDrive\mingw.7z"""); `
    `
    $sha256 = 'e8c65ddc655534b0330f66f7b480565621e8617cda9937d76ba141a22bf3b2fa'; `
    Write-Host ('Verifying SHA256 ({0}) ...' -f $sha256); `
    if ((Get-FileHash $env:SystemDrive\mingw.7z -Algorithm sha256).Hash -ne $sha256) { `
        Write-Host 'Checksum Mingw-w64 failed!'; `
        exit 1; `
    }; `
    `
    Write-Host 'Installing ...'; `
    7z x $env:SystemDrive\mingw.7z; `
    Write-Host 'Removing downloaded...'; `
    Remove-Item -Force -Path $env:SystemDrive\mingw.7z; `
    $env:PATH = [string]::Format('{0}\mingw64\bin;', $env:SystemDrive) + $env:PATH; `
    [Environment]::SetEnvironmentVariable('PATH', $env:PATH, [EnvironmentVariableTarget]::Machine); `
    `
    Write-Host 'Verifying install ("mingw32-make -v") ...'; `
    mingw32-make -v; `
    `
    Write-Host ('Downloading {0} ...' -f $env:VS_BUILDTOOLS_URL); `
    [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; `
    Invoke-WebRequest -OutFile $env:SystemDrive\vs_buildtools.exe $env:VS_BUILDTOOLS_URL; `
    `
    Write-Host ('{0} - Visual Studio components installing...' -f $(Get-Date -format 'u')); `
    cmd /C start /w $env:SystemDrive\vs_buildtools.exe `
        --quiet `
        --wait `
        --norestart `
        --nocache `
        --installPath """${env:ProgramFiles(x86)}\Microsoft Visual Studio\2019\BuildTools""" `
        --channelUri https://aka.ms/vs/16/release/channel `
        --installChannelUri https://aka.ms/vs/16/release/channel `
        --channelId VisualStudio.16.Release `
        # https://docs.microsoft.com/en-us/visualstudio/install/workload-component-id-vs-build-tools?view=vs-2019
        --add Microsoft.VisualStudio.Component.VC.CMake.Project; `
    if ($err = dir $Env:TEMP -Filter dd_setup_*_errors.log | where Length -gt 0 | Get-Content) { `
        throw $err; `
    }; `
    Wait-Process -name msiexec; `
    Write-Host ('{0} - Visual Studio components installed' -f $(Get-Date -format 'u')); `
    `
    Write-Host 'Visual Studio components installation cleanup'; `
    Write-Host 'Removing downloaded...'; `
    Remove-Item -Force -Path $env:SystemDrive\vs_buildtools.exe; `
    Get-ChildItem -Path """${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer""" -Directory -Recurse | Remove-Item -Force -Recurse; `
    Remove-Item -Force -Recurse $env:TEMP\*; `
    Write-Host 'Build environment is ready...';

RUN Set-Location -Path $env:SystemDrive\.; `
    `
    Import-Module ('{0}\Microsoft Visual Studio\2019\BuildTools\Common7\Tools\Microsoft.VisualStudio.DevShell.dll' -f ${env:ProgramFiles(x86)} ); `
    Enter-VsDevShell -VsInstallPath ('{0}\Microsoft Visual Studio\2019\BuildTools' -f ${env:ProgramFiles(x86)}) -DevCmdArguments """-arch=$env:BUILD_ARCH"""; `
    `
    Write-Host ('Downloading {0} ...' -f $env:PCRE2_URL); `
    [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; `
        Invoke-WebRequest -OutFile $env:SystemDrive\pcre2.zip -Uri $env:PCRE2_URL; `
    `
    $sha256 = '08a8861f60fec3af30ca1e0f51d89ab5dc5c07bb71b74db5297f78b7e26c7226'; `
    Write-Host ('Verifying SHA256 ({0}) ...' -f $sha256); `
    if ((Get-FileHash $env:SystemDrive\pcre2.zip -Algorithm sha256).Hash -ne $sha256) { `
        Write-Host 'Checksum PCRE2 library failed!'; `
        exit 1; `
    }; `
    Write-Host 'Extracting archive ...'; `
    Expand-Archive -Path $env:SystemDrive\pcre2.zip -DestinationPath $env:SystemDrive; `
    Write-Host 'Removing downloaded...'; `
    Remove-Item -Force -Path $env:SystemDrive\pcre2.zip; `
    Rename-Item -Path $env:SystemDrive\pcre2-$env:PCRE2_VERSION -NewName $env:SystemDrive\pcre2_build; `
    `
    Set-Location -Path $env:SystemDrive\pcre2_build; `
    Write-Host 'Building PCRE2 library ...'; `
    cmake --log-level=ERROR `
        -G 'MinGW Makefiles' `
        -DBUILD_SHARED_LIBS=OFF `
        -DCMAKE_C_COMPILER=gcc `
        -DCMAKE_C_FLAGS='-O2 -g' `
        -DCMAKE_INSTALL_PREFIX="""$env:SystemDrive\pcre2_output""" . ; `
    mingw32-make -s -j"""$env:NUMBER_OF_PROCESSORS"""; `
    mingw32-make -s -j"""$env:NUMBER_OF_PROCESSORS""" install; `
    Write-Host 'PCRE2 is ready...';

RUN Set-Location -Path $env:SystemDrive\.; `
    `
    Write-Host ('Downloading {0} ...' -f $env:CYGWIN_URL); `
    [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; `
    (New-Object Net.WebClient).DownloadFile("""$env:CYGWIN_URL""", """$env:SystemDrive\setup.exe"""); `
    `
    $sha256 = 'edd0a64dc65087ffe453ca94b267169b39458a983b29ac31320fcaa983d0f97e'; `
    Write-Host ('Verifying SHA256 ({0}) ...' -f $sha256); `
    if ((Get-FileHash $env:SystemDrive\setup.exe -Algorithm sha256).Hash -ne $sha256) { `
        Write-Host 'Checksum Cygwin failed!'; `
        exit 1; `
    }; `
    Write-Host 'Installing ...'; `
    Start-Process $env:SystemDrive\setup.exe `
        -ArgumentList """-qnNdO -a x86_64 -R $env:SystemDrive\cygwin --site http://cygwin.mirror.constant.com -l $env:SystemDrive\cygwin\var\cache\setup --packages perl""" `
        -Wait `
        -NoNewWindow; `
    `
    Write-Host 'Removing downloaded...'; `
    Remove-Item -Force -Path $env:SystemDrive\setup.exe; `
    Write-Host ('Downloading {0} ...' -f $env:OPENSSL_URL); `
    [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; `
    Invoke-WebRequest -OutFile $env:SystemDrive\openssl.tar.gz -Uri $env:OPENSSL_URL; `
    `
    $sha256 = '6c13d2bf38fdf31eac3ce2a347073673f5d63263398f1f69d0df4a41253e4b3e'; `
    Write-Host ('Verifying SHA256 ({0}) ...' -f $sha256); `
    if ((Get-FileHash $env:SystemDrive\openssl.tar.gz -Algorithm sha256).Hash -ne $sha256) { `
        Write-Host 'Checksum OpenSSL library failed!'; `
        exit 1; `
    }; `
    `
    Write-Host 'Extracting archive ...'; `
    tar -zxf $env:SystemDrive\openssl.tar.gz; `
    Write-Host 'Removing downloaded...'; `
    Remove-Item -Force -Path $env:SystemDrive\openssl.tar.gz; `
    Rename-Item -Path $env:SystemDrive\openssl-$env:OPENSSL_VERSION -NewName $env:SystemDrive\openssl_build; `
    `
    Write-Host 'Building OpenSSL library...'; `
    Set-Location -Path $env:SystemDrive\openssl_build; `
    $env:PATH+=""";$env:SystemDrive\cygwin\bin"""; `
    perl Configure `
        mingw64 `
        no-shared `
        no-ui-console `
        no-tests `
#        enable-capieng `
        no-capieng `
        --api=1.1.0 `
        --libdir=lib `
        --prefix=$env:SystemDrive/openssl_output `
        --openssldir=$env:SystemDrive/openssl_output_ssl; `
    mingw32-make -s -j"""$env:NUMBER_OF_PROCESSORS""" build_sw; `
    mingw32-make -s -j"""$env:NUMBER_OF_PROCESSORS""" install_dev; `
    Write-Host 'OpenSSL is ready...'; `
    Write-Host 'Removing cygwin...'; `
    Remove-Item -Recurse -Force -Path $env:SystemDrive\cygwin;
