# Based on https://randywestergren.com/building-pyodbc-for-lambdas-python-3-9-runtime/
# Maybe we could develop this into something close to these ones but for Lambda 3.9 which should make it more robust https://github.com/davidcomerford/pyodbc-mssql-lambda-layer
FROM public.ecr.aws/lambda/python:3.9 as builder


ENV ODBCINI=/opt/odbc.ini
ENV ODBCSYSINI=/opt/
ARG UNIXODBC_VERSION=2.3.9


#{------------------------ Openssl SnapSafe Fix ------------------------ #
RUN <<EOF
cat > /etc/yum.repos.d/amzn2-extras.repo << 'EOREPO'
[amzn2extra-openssl-snapsafe]
name=Amazon Extras repo for openssl-snapsafe
enabled=1
mirrorlist=$awsproto://$amazonlinux.$awsregion.$awsdomain/2/extras/openssl-snapsafe/latest/$basearch/mirror.list
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-amazon-linux-2
priority=10
skip_if_unavailable=1
report_instanceid=yes
EOREPO
EOF

RUN yum upgrade -y openssl-snapsafe-libs
#{--------- Bases on aws-lambda-base-images/issues/245#issuecomment-2718804385  --------- #


RUN yum install -y gzip tar openssl-devel && yum groupinstall "Development Tools" -y
RUN curl https://www.unixodbc.org/unixODBC-${UNIXODBC_VERSION}.tar.gz -O \
    && tar xzvf unixODBC-${UNIXODBC_VERSION}.tar.gz \
    && cd unixODBC-${UNIXODBC_VERSION} \
    && ./configure --sysconfdir=/opt --disable-gui --disable-drivers --enable-iconv --with-iconv-char-enc=UTF8 --with-iconv-ucode-enc=UTF16LE --prefix=/opt \
    && make \
    && make install

RUN curl https://packages.microsoft.com/config/rhel/6/prod.repo > /etc/yum.repos.d/mssql-release.repo
RUN yum install e2fsprogs.x86_64 0:1.43.5-2.43.amzn1 fuse-libs.x86_64 0:2.9.4-1.18.amzn1 libss.x86_64 0:1.43.5-2.43.amzn1 -y
RUN ACCEPT_EULA=Y yum install -y msodbcsql17

ENV CFLAGS="-I/opt/include"
ENV LDFLAGS="-L/opt/lib"


FROM public.ecr.aws/lambda/python:3.9


COPY --from=builder /opt/microsoft /opt/microsoft
COPY --from=builder /opt/lib /opt/lib