# ---------- build stage ----------
FROM --platform=linux/amd64 mcr.microsoft.com/dotnet/sdk:9.0 AS build
WORKDIR /src

# Install tools needed to install IBM i Access ODBC (alien to convert RPM, unixODBC dev for headers)
RUN apt-get update && apt-get install -y --no-install-recommends \
    alien curl ca-certificates unzip \
    unixodbc unixodbc-dev \
    && rm -rf /var/lib/apt/lists/*

# Ensure directories exist even if the IBM driver is absent, so later COPY succeeds
RUN mkdir -p /opt/ibm /usr/lib /usr/lib64 /tmp/odbc-libs/lib /tmp/odbc-libs/lib64

# Copy IBM i Access ODBC RPM from build context (put your rpm under ./drivers)
# Example filename: ibm-iaccess-1.1.0.29-1.0.x86_64.rpm.disabled (we drop the .disabled suffix below)
COPY drivers/ /tmp/drivers/
RUN set -ex; \
    if ls /tmp/drivers/ibm-iaccess-*.rpm.disabled >/dev/null 2>&1; then \
      for f in /tmp/drivers/ibm-iaccess-*.rpm.disabled; do mv "$f" "${f%.disabled}"; done; \
    fi
RUN set -ex; \
    if ls /tmp/drivers/ibm-iaccess-*.rpm >/dev/null 2>&1; then \
      for f in /tmp/drivers/ibm-iaccess-*.rpm; do alien -i --scripts "$f"; done; \
    else echo ">> IBM i Access ODBC RPM not found in /tmp/drivers. Build will continue, but ODBC will not work until driver is present." ; fi

# Collect IBM driver shared libraries so they can be copied without optional globs later
RUN set -ex; \
    if ls /opt/ibm/iaccess/lib64/libcwb*.so* >/dev/null 2>&1; then cp /opt/ibm/iaccess/lib64/libcwb*.so* /tmp/odbc-libs/lib64/; fi; \
    if ls /opt/ibm/iaccess/lib/libcwb*.so* >/dev/null 2>&1; then cp /opt/ibm/iaccess/lib/libcwb*.so* /tmp/odbc-libs/lib/; fi

# Register ODBC driver (odbcinst.ini)
COPY docker/odbc/odbcinst.ini /etc/odbcinst.ini
# Optional DSN (odbc.ini) if you prefer DSN connections
COPY docker/odbc/odbc.ini /etc/odbc.ini

# copy project and restore/build
COPY AS400API.csproj ./
RUN dotnet restore AS400API.csproj
COPY . .
RUN dotnet publish AS400API.csproj -c Release -o /app/publish /p:UseAppHost=false

# ---------- runtime stage ----------
FROM --platform=linux/amd64 mcr.microsoft.com/dotnet/aspnet:9.0 AS final
WORKDIR /app

# Install unixODBC and copy IBM i Access ODBC libs from build stage
RUN apt-get update && apt-get install -y --no-install-recommends \
    unixodbc \
    && rm -rf /var/lib/apt/lists/*

# Copy IBM i driver files installed in build stage (if present)
# Common path after installing ibm-iaccess via alien:
COPY --from=build /opt/ibm /opt/ibm
COPY --from=build /tmp/odbc-libs/lib64/ /usr/lib64/
COPY --from=build /tmp/odbc-libs/lib/ /usr/lib/

# ODBC config
COPY docker/odbc/odbcinst.ini /etc/odbcinst.ini
COPY docker/odbc/odbc.ini /etc/odbc.ini

# App
COPY --from=build /app/publish .

# Default envs (override in compose)
ENV ASPNETCORE_URLS=http://+:8080
ENV AS400_DRIVER_NAME="IBM i Access ODBC Driver"
ENV LD_LIBRARY_PATH=/opt/ibm/iaccess/lib64:/opt/ibm/iaccess/lib

EXPOSE 8080
ENTRYPOINT ["dotnet", "AS400API.dll"]
