# Use the rust image as the base image for the build stage
FROM rust:latest AS builder

# Copy the rust-teos source code
COPY . /tmp/rust-teos

# Install the dependencies required for building rust-teos
RUN apt-get update\
    && apt-get -y --no-install-recommends install libffi-dev libssl-dev musl-tools pkg-config

RUN cd /tmp/rust-teos \
    && rustup target add x86_64-unknown-linux-musl \
    # Rustfmt is needed to format the grpc stubs generated by tonic
    && rustup component add rustfmt \
    # Cross compile with musl as the target, so teosd can run on alpine
    && RUSTFLAGS='-C target-feature=+crt-static' cargo build --manifest-path=teos/Cargo.toml --locked --release --target x86_64-unknown-linux-musl

# Use a new stage with a smaller base image to reduce image size
FROM alpine:latest

RUN apk update && apk upgrade

# UID and GID for the teosd user
ENV TEOS_UID=1001 TEOS_GID=1001

# Copy the teos binaries from the build stage to the new stage
COPY --from=builder \
    /tmp/rust-teos/target/x86_64-unknown-linux-musl/release/teosd \
    /tmp/rust-teos/target/x86_64-unknown-linux-musl/release/teos-cli /usr/local/bin/

# Copy the entrypoint script to the container
COPY docker/entrypoint.sh /entrypoint.sh

# Set the entrypoint script as executable and add running user
RUN chmod +x /entrypoint.sh \
    && addgroup -g ${TEOS_GID} -S teos \
    && adduser -S -G teos -u ${TEOS_UID} teos

# Expose the default port used by teosd
EXPOSE 9814/tcp

# Switch user so that we don't run stuff as root
USER teos

# Create the teos data directory
RUN mkdir /home/teos/.teos

# Start teosd when the container starts
ENTRYPOINT [ "/entrypoint.sh" ]