#!/usr/bin/with-contenv bash

# create folders
mkdir -p \
  /config/storage \
  /config/uploads

# copy config files
PREV_DIR=$(pwd)

cd /defaults/storage || exit
shopt -s globstar nullglob
for i in *; do
  [[ ! -e "/config/storage/${i}" ]] && cp -r "${i}" "/config/storage/${i}"
done

cd /defaults/uploads || exit
shopt -s globstar nullglob
for i in *; do
  [[ ! -e "/config/uploads/${i}" ]] && cp -r "${i}" "/config/uploads/${i}"
done
cd "${PREV_DIR}" || exit

# make symlinks
[[ ! -L /var/www/html/storage ]] && \
  ln -sf /config/storage /var/www/html/storage
[[ ! -L /var/www/html/public/uploads ]] && \
  ln -sf /config/uploads /var/www/html/public/uploads

# create API key if needed
if [ ! -f "/config/SNIPE_IT_APP_KEY.txt" ]
then
  echo "Generating SnipeIT app key for first run"
  key=$(php /var/www/html/artisan key:generate --show)
  echo $key > /config/SNIPE_IT_APP_KEY.txt
  echo "App Key set to $key you can modify the file to update /config/SNIPE_IT_APP_KEY.txt"
fi

# permissions
chown -R abc:abc \
  /config/ \
  /var/www/html/bootstrap/cache

# add server name to nginx config while handling legacy settings
if [ ! -z ${NGINX_APP_URL+x} ]; then
  REPLACE_URL=${NGINX_APP_URL}
fi
if [ ! -z ${NGINX_APP_URL+x} ] && [ -z ${APP_URL+x} ]; then
  printf "http://${NGINX_APP_URL}" > /run/s6/container_environment/APP_URL
fi
if [ -z ${NGINX_APP_URL+x} ] && [ ! -z ${APP_URL+x} ]; then
  REPLACE_URL=$(echo ${APP_URL} | awk -F/ '{print $3}')
fi
sed -i "s/APP_URL_PLACEHOLDER/${REPLACE_URL}/g" /config/nginx/site-confs/default

# if the Oauth DB files are not present copy the vendor files over to the db migrations
if [ ! -f "/var/www/html/database/migrations/*create_oauth*" ]; then
  cp -ax /var/www/html/vendor/laravel/passport/database/migrations/* /var/www/html/database/migrations/
fi

# if this container is setup run migrate
if [ -f /config/storage/oauth-public.key ]; then
  php /var/www/html/artisan migrate --force
fi

# copy over timezone env var
if [ ! -z ${TZ+x} ]; then
  printf ${TZ} > /run/s6/container_environment/APP_TIMEZONE
fi
