#!/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
sed -i "s/APP_URL_PLACEHOLDER/${APP_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
