
FROM alpine:3.15

# vim and bash for debug
RUN apk update && apk add \
	nginx openssl \
	vim bash \
	&& \
	rm -rf /var/cache/apk*

# nginx conf
COPY ./conf/nginx_main.conf.alpine /etc/nginx/nginx.conf
COPY ./conf/nginx_http_server.conf /etc/nginx/http.d/
# dir for logs
RUN mkdir -p /var/log/nginx/

# create user www-data and assign it to group www-data
RUN adduser -S www-data && \
	adduser www-data www-data && \
	adduser www-data nginx && \
	chmod +rwx /var/lib/nginx/tmp

# ARG variables are not persistent after the build process, in opposite to ENV
ARG WP_URL
ARG WP_VOLUME_DIR
ARG WP_VOLUME_PLUGINS
ARG NG_CERTS_DIR
ARG SERVER_MAX_UPLOAD_SIZE

# IS IT USEFUL ?
# # create and empty volumes dir
# RUN mkdir -p ${WP_VOLUME_DIR}   ${WP_VOLUME_PLUGINS}   && \
# 	rm -rf     ${WP_VOLUME_DIR}/* ${WP_VOLUME_PLUGINS}/*


# replace WP_URL
RUN sed -i "s/\${WP_URL}/${WP_URL}/g" /etc/nginx/http.d/nginx_http_server.conf
# replace max file size upload
RUN sed -i "s/\(client_max_body_size \).*\(m;\)/\1${SERVER_MAX_UPLOAD_SIZE}\2/g" /etc/nginx/nginx.conf

# create ssl certificates
#   command openssl :
#    - req             : create a certificate signing request (CSR) or a self-signed certificate
#    - newkey rsa:2048 : generate a new RSA key pair with a key length of 2048 bits
#    - nodes           : the private key should not be encrypted with a passphrase. This is useful for automated processes where entering a passphrase is not practical
#    - x509            : a self-signed certificate should be created
#    - days 365        : sets the validity period of the certificate to 365 days
#    - subj            : sets the subject, information about the entity the certificate is issued to
#      - C, ST, L, O, OU, CN : country, state, locality, organization, organizational unit, and common name
#    - keyout          : the filename for the private key file
#    - out             : the filename for the output certificate file
ARG SSL_KEY=${NG_CERTS_DIR}/private/${WP_URL}.key
ARG SSL_CERT=${NG_CERTS_DIR}/certs/${WP_URL}.crt
RUN mkdir -p ${NG_CERTS_DIR}; \
		cd ${NG_CERTS_DIR}; \
		mkdir private certs; \
		openssl req -newkey rsa:2048 -nodes -x509 -days 365 \
			-subj "/C=fr/ST=ile-de-france/L=paris/O=wp/OU=wp_local/CN=${WP_URL}" \
			-keyout ${SSL_KEY} \
			-out ${SSL_CERT};

ENTRYPOINT [ "nginx", "-g", "daemon off;" ]

