######################
##  Build Frontend  ##
######################

FROM --platform=$BUILDPLATFORM node:alpine AS build-frontend
WORKDIR /src

# Define base address
ARG BASE_URL=/

# Install the angular CLI
RUN npm install -g @angular/cli

# Copy the package.json into this build step
COPY  ./src/Client/package.json ./

# Pull dependencies
RUN npm install

# Copy the rest of the frontend over
COPY ./src/Client/ ./

# Compile the source
RUN ng build --base-href=${BASE_URL}

#####################
##  Build Backend  ##
#####################

FROM --platform=$BUILDPLATFORM mcr.microsoft.com/dotnet/sdk:9.0 AS build-backend
WORKDIR /src

# Copy the csproj
COPY ./src/Server/Server.csproj ./

# Restore the Server
RUN dotnet restore './Server.csproj'

# Copy the rest of the backend over
COPY ./src/Server/ ./

# Get the target arch
ARG TARGETARCH

# Build the source
RUN set -e && \
    if [ "$TARGETARCH" = "arm64" ]; then RID="linux-arm64"; \
    elif [ "$TARGETARCH" = "amd64" ]; then RID="linux-x64"; \
    else echo "Unsupported ARCH: $TARGETARCH"; exit 1; \
    fi && \
    dotnet publish './Server.csproj' -c Release -r ${RID} -o /app/publish

################
##  Publish   ##
################

FROM mcr.microsoft.com/dotnet/aspnet:9.0

WORKDIR /certs
RUN apt update && apt upgrade -y && \
    apt install -y openssl && \
    openssl genrsa -out private_key.pem 2048 && \
    openssl rsa -in private_key.pem -pubout -out public_key.pem

WORKDIR /app

ENV ASPNETCORE_HTTP_PORTS=5000
ENV StripeKey=null
ENV MySQLServer=null
ENV MySQLUser=null
ENV MySQLPass=null
ENV MySQLDatabase=Mistox

EXPOSE 5000

# Copy in the server
COPY --from=build-backend /app/publish ./

# Copy in the client
COPY --from=build-frontend /debug/wwwroot ./wwwroot/

ENTRYPOINT ["dotnet", "Server.dll", "--url", "http://localhost:5000"]