# Dockerfile

ARG         AWS_ACCOUNT=086679231553

FROM        ${AWS_ACCOUNT}.dkr.ecr.us-east-1.amazonaws.com/docker-parent-images:python314 AS base

WORKDIR     /var/app

# Update and install common packages
USER        root
RUN         apt update -y
RUN         apt install -y zip
RUN         apt-get install -y --no-install-recommends gcc libc6-dev

# Create and configure virtualenv and gunicorn
ENV         VIRTUAL_ENV /var/env
RUN         python -m venv ${VIRTUAL_ENV}
ENV         PATH "$VIRTUAL_ENV/bin:$PATH"

RUN         pip install --upgrade pip
RUN         pip install gunicorn
RUN         useradd gunicorn -s /bin/false

# Add application and install requirements
ADD         requirements.txt ./
RUN         apt-get -y install gcc
RUN         if [ -f /var/app/requirements.txt ]; then pip install -I -r /var/app/requirements.txt; fi
RUN         apt-get remove -y gcc && apt-get -y autoremove && apt-get -y autoclean && rm -rf /var/lib/apt/lists/*
ADD         . /var/app

# Build image for live deployment
FROM        base AS deploy

# Remove tests
RUN         rm -rf /var/app/tests

# Setup environment
ENV         LC_ALL=en_US.utf-8
ENV         LC_CTYPE=en_US.UTF-8

# Setup Snowflake env
RUN         mkdir /var/app/.snowflake
RUN         chmod 777 /var/app/.snowflake
ENV         SNOWFLAKE_HOME=/var/app/

# Add startup script
ADD         gunicorn-start.sh /
RUN         chmod +x /gunicorn-start.sh
USER        worker
ENTRYPOINT  ["./gunicorn-start.sh"]

EXPOSE      8080

# Build the dev stage
FROM        base AS dev

ENV         PATH "$VIRTUAL_ENV/bin:$PATH"

# Copy Files
COPY        moneyhub application.py dev.py ./

# Enables prints in python to flush to stdout
ENV         PYTHONUNBUFFERED 1

# Start dev server
CMD         ["var/app/dev.py", "2>&1"]


# Build the lint and test stage
FROM        base AS lint_and_unit_test

ENV         PATH "$VIRTUAL_ENV/bin:$PATH"

ADD         requirements-dev.txt ./
RUN         pip install -r requirements-dev.txt

ADD         lint-and-unit-test.sh dev.py application.py setup.cfg ./
COPY        moneyhub/* ./moneyhub
COPY        scripts/* ./scripts
COPY        tests/* ./tests

ENTRYPOINT  ["./lint-and-unit-test.sh"]


# Build the lint and test stage
FROM        base AS integration_test

ENV         PATH "$VIRTUAL_ENV/bin:$PATH"

RUN         pip install -r /var/app/requirements-dev.txt
RUN         pip install -q -i https://pypi.theorchard.io/pypi/ qa-testing-utils


ADD         integration-test.sh dev.py application.py setup.cfg ./
COPY        moneyhub/* ./moneyhub
COPY        tests/* ./tests

ENTRYPOINT  ["./integration-test.sh"]


# Run scripts
FROM        base AS script_runner

COPY        moneyhub scripts

ENV         PATH "$VIRTUAL_ENV/bin:$PATH"
ENV         PYTHONUNBUFFERED 1

ADD         script-runner.sh backfill.csv
ENTRYPOINT  ["./script-runner.sh"]
