FROM alpine:3.22 AS base
WORKDIR /app

FROM mcr.microsoft.com/dotnet/sdk:9.0 AS build
WORKDIR /src

COPY ["RobotNet.IdentityServer/RobotNet.IdentityServer.csproj", "RobotNet.IdentityServer/"]
COPY ["RobotNet.IdentityServer/libman.json", "RobotNet.IdentityServer/"]
COPY ["RobotNet.ServiceDefaults/RobotNet.ServiceDefaults.csproj", "RobotNet.ServiceDefaults/"]

# RUN dotnet package remove "Microsoft.EntityFrameworkCore.Tools" --project "RobotNet.IdentityServer/RobotNet.IdentityServer.csproj"
RUN dotnet restore "RobotNet.IdentityServer/RobotNet.IdentityServer.csproj"

WORKDIR /src/RobotNet.IdentityServer
RUN dotnet tool install -g Microsoft.Web.LibraryManager.Cli
ENV PATH="${PATH}:/root/.dotnet/tools"
# RUN libman restore

WORKDIR /src
COPY RobotNet.IdentityServer/ RobotNet.IdentityServer/
COPY RobotNet.ServiceDefaults/ RobotNet.ServiceDefaults/

RUN rm -rf ./RobotNet.IdentityServer/bin
RUN rm -rf ./RobotNet.IdentityServer/obj
RUN rm -rf ./RobotNet.ServiceDefaults/bin
RUN rm -rf ./RobotNet.ServiceDefaults/obj

WORKDIR "/src/RobotNet.IdentityServer"
RUN dotnet build -c Release -o /app/build

FROM build AS publish
WORKDIR /src/RobotNet.IdentityServer
RUN dotnet publish "RobotNet.IdentityServer.csproj" \ 
    -c Release \
    -o /app/publish \
    --runtime linux-musl-x64 \
    --self-contained true \
    /p:PublishTrimmed=false \
    /p:PublishReadyToRun=true

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish ./

RUN apk add --no-cache icu-libs tzdata ca-certificates

RUN echo '#!/bin/sh' >> ./start.sh
RUN echo 'update-ca-certificates' >> ./start.sh
RUN echo 'exec ./RobotNet.IdentityServer' >> ./start.sh

RUN chmod +x ./RobotNet.IdentityServer
RUN chmod +x ./start.sh

# Use the start script to ensure certificates are updated before starting the application
EXPOSE 443
ENTRYPOINT ["./start.sh"]