# Copyright 2020 The Kubernetes Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

ARG BASEIMAGE
from $BASEIMAGE as prep

ENV CURL_VERSION=7.57.0 \
    PS_VERSION=6.2.0
WORKDIR /curl
ADD https://skanthak.homepage.t-online.de/download/curl-$CURL_VERSION.cab curl.cab
ADD https://github.com/PowerShell/PowerShell/releases/download/v$PS_VERSION/PowerShell-$PS_VERSION-win-x64.zip /PowerShell/powershell.zip
ADD https://eternallybored.org/misc/netcat/netcat-win32-1.12.zip /netcat//netcat.zip

USER ContainerAdministrator
RUN expand /R curl.cab /F:* . &\
    cd C:\PowerShell &\
    tar.exe -xf powershell.zip &\
    del powershell.zip &\
    mklink powershell.exe pwsh.exe &\
    cd C:\netcat &\
    tar.exe -xf netcat.zip &\
    del netcat.zip

FROM $BASEIMAGE

COPY --from=prep /curl/AMD64 /curl/CURL.LIC /curl/
COPY --from=prep ["/PowerShell", "/Program Files/PowerShell"]
COPY --from=prep /netcat/nc64.exe /bin/nc.exe
ADD https://github.com/kubernetes-sigs/windows-testing/raw/master/images/busybox/busybox.exe /bin/busybox.exe
ADD hostname /bin/hostname.exe

USER ContainerAdministrator
RUN FOR /f "tokens=*" %i IN ('C:\bin\busybox --list') DO mklink C:\bin\%i.exe C:\bin\busybox.exe
# Set the path
RUN setx /M PATH "C:\bin;C:\curl\;%PATH%;C:\Program Files\PowerShell;" &\
    mkdir C:\tmp

# Copy PowerShell Core from the installer container
ENV ProgramFiles="C:\Program Files" \
    # set a fixed location for the Module analysis cache
    LOCALAPPDATA="C:\Users\ContainerAdministrator\AppData\Local" \
    PSModuleAnalysisCachePath="$LOCALAPPDATA\Microsoft\Windows\PowerShell\docker\ModuleAnalysisCache" \
    # Persist %PSCORE% ENV variable for user convenience
    PSCORE="$ProgramFiles\PowerShell\pwsh.exe"

# intialize powershell module cache
RUN powershell \
        -NoLogo \
        -NoProfile \
        -Command " \
          $stopTime = (get-date).AddMinutes(15); \
          $ErrorActionPreference = 'Stop' ; \
          $ProgressPreference = 'SilentlyContinue' ; \
          while(!(Test-Path -Path $env:PSModuleAnalysisCachePath)) {  \
            Write-Host "'Waiting for $env:PSModuleAnalysisCachePath'" ; \
            if((get-date) -gt $stopTime) { throw 'timout expired'} \
            Start-Sleep -Seconds 6 ; \
          }"

ENTRYPOINT ["cmd.exe", "/s", "/c"]
