#!/bin/bash
set -e

USER={{user}}

# Set default UID:GID values
ELASTIC_UID=${ELASTIC_UID:-1000}
ELASTIC_GID=${ELASTIC_GID:-1000}


## Change UID:GID for `{{user}}` user to passed in values
# A nasty side effect of `usermod` is chown of home directory,
# so in order to avoid it we're changing it from `/usr/share/kibana`
usermod -u $ELASTIC_UID -d '' $USER
groupmod -g $ELASTIC_GID $USER
usermod -a -G root $USER

# Change owner UID:GID for directories required to be written to
chown -hR $USER: /app /tmp

shopt -s extglob
# Install startup scripts
if [ -d "/app/etc/my_init.d" ]; then
    mkdir -p /etc/my_init.d
    # we copy everything except potential leftovers .new files that can be generated by the allocator
    cp -f /app/etc/my_init.d/!(*.new) /etc/my_init.d/
    chmod -R +x /etc/my_init.d/
fi
shopt -u extglob

exec /sbin/my_init --skip-runit -- setuser $USER /app/kibana.sh
