FROM alpine:3.22 AS base
WORKDIR /app

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

COPY ["RobotNet.RobotManager/RobotNet.RobotManager.csproj", "RobotNet.RobotManager/"]
COPY ["RobotNet.RobotShares/RobotNet.RobotShares.csproj", "RobotNet.RobotShares/"]
COPY ["RobotNet.MapShares/RobotNet.MapShares.csproj", "RobotNet.MapShares/"]
COPY ["RobotNet.Script/RobotNet.Script.csproj", "RobotNet.Script/"]
COPY ["RobotNet.Script.Expressions/RobotNet.Script.Expressions.csproj", "RobotNet.Script.Expressions/"]
COPY ["RobotNet.Shares/RobotNet.Shares.csproj", "RobotNet.Shares/"]
COPY ["RobotNet.OpenIddictClient/RobotNet.OpenIddictClient.csproj", "RobotNet.OpenIddictClient/"]
COPY ["RobotNet.Clients/RobotNet.Clients.csproj", "RobotNet.Clients/"]

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

COPY RobotNet.RobotManager/ RobotNet.RobotManager/
COPY RobotNet.RobotShares/ RobotNet.RobotShares/
COPY RobotNet.MapShares/ RobotNet.MapShares/
COPY RobotNet.Script/ RobotNet.Script/
COPY RobotNet.Script.Expressions/ RobotNet.Script.Expressions/
COPY RobotNet.Shares/ RobotNet.Shares/
COPY RobotNet.OpenIddictClient/ RobotNet.OpenIddictClient/
COPY RobotNet.Clients/ RobotNet.Clients/

RUN rm -rf ./RobotNet.RobotManager/bin
RUN rm -rf ./RobotNet.RobotManager/obj
RUN rm -rf ./RobotNet.RobotShares/bin
RUN rm -rf ./RobotNet.RobotShares/obj
RUN rm -rf ./RobotNet.MapShares/bin
RUN rm -rf ./RobotNet.MapShares/obj
RUN rm -rf ./RobotNet.Script/bin
RUN rm -rf ./RobotNet.Script/obj
RUN rm -rf ./RobotNet.Script.Expressions/bin
RUN rm -rf ./RobotNet.Script.Expressions/obj
RUN rm -rf ./RobotNet.Shares/bin
RUN rm -rf ./RobotNet.Shares/obj
RUN rm -rf ./RobotNet.OpenIddictClient/bin
RUN rm -rf ./RobotNet.OpenIddictClient/obj
RUN rm -rf ./RobotNet.Clients/bin
RUN rm -rf ./RobotNet.Clients/obj

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

FROM build AS publish
WORKDIR /src/RobotNet.RobotManager
RUN dotnet publish "RobotNet.RobotManager.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.RobotManager' >> ./start.sh

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

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