# arguments
ARG VERSION="master"
# Branch to check out
ARG CHECKOUT_BRANCH="master"

FROM node:lts AS build

#environment variables
ENV PROJECT_NAME="headscale-ui"
# URL for the github/git location
ENV PROJECT_URL="https://github.com/gurucomputing/headscale-ui"

# Set the staging environment
WORKDIR /staging/scripts
WORKDIR /staging
RUN chown 1000:1000 /staging

# Copy across the scripts folder
COPY scripts/* ./scripts/

# Set permissions for all scripts. We do not want normal users to have write
# access to the scripts
RUN chown -R 0:0 scripts
RUN chmod -R 755 scripts

# Build the image. This build runs as root
RUN /staging/scripts/1-image-build.sh

#####
## Second Image
#####

FROM alpine:latest

#environment variables
ENV PROJECT_NAME="headscale-ui"
# URL for the github/git location
ENV PROJECT_URL="https://github.com/gurucomputing/headscale-ui"
# Ports that caddy will run on
ENV HTTP_PORT="80"
ENV HTTPS_PORT="443"

# Production Web Server port. Runs a self signed SSL certificate
EXPOSE 443

# Set the staging environment
WORKDIR /data
WORKDIR /web
WORKDIR /staging/scripts
WORKDIR /staging

# Copy across the scripts folder
COPY scripts/* ./scripts/
# Copy default caddy config from project root
COPY ./Caddyfile /staging/Caddyfile
COPY --from=build /staging/${PROJECT_NAME}/build /web

RUN apk add --no-cache caddy

# Create a group and user
RUN addgroup -S appgroup && adduser -D appuser -G appgroup

# Set permissions for all scripts. We do not want normal users to have write
# access to the scripts
RUN chown -R 0:0 scripts
RUN chmod -R 755 scripts

RUN chown -R appuser:appgroup /web
RUN chown -R appuser:appgroup /data

# Tell docker that all future commands should run as the appuser user
USER appuser

WORKDIR /data

ENTRYPOINT /bin/sh /staging/scripts/2-initialise.sh