#!/bin/sh

# This script configures the VM for the allowed-images feature.

# shellcheck shell=ash

set -o errexit -o nounset

# Create nobody user and group for nginx.
addgroup -S -g 65534 nobody 2>/dev/null || true
adduser -S -D -H -h /dev/null -s /sbin/nologin -u 65534 -G nobody -g nobody nobody 2>/dev/null || true

# Install mkcert and create default certs for localhost.
export CAROOT=/run/mkcert
mkdir -p $CAROOT
cd $CAROOT
mkcert -install
mkcert localhost
chown -R nobody:nobody $CAROOT

# configure proxy only when allowed-images exists
allowed_images_conf=/usr/local/openresty/nginx/conf/allowed-images.conf
setproxy="[ -f $allowed_images_conf ] && supervise_daemon_args=\"-e HTTPS_PROXY=http://127.0.0.1:3128 \${supervise_daemon_args:-}\" || true"
sed -i "\#-f $allowed_images_conf#d" /etc/init.d/containerd
echo "$setproxy" >> /etc/init.d/containerd

# openresty is backgrounding itself (and writes its own pid file)
sed -i 's/^command_background/#command_background/' /etc/init.d/rd-openresty

# Make sure openresty log directory exists
install -d -m755 /var/log/openresty
