#!/bin/bash

# enable strict mode
set -euo pipefail
IFS=$'\n\t'

# Make sure directories are writable
WRITABLE_DIRECTORIES=('application/Proxies' 'public/tmp')
# APP_HOME is provided by the Dockerfile

for DIR in "${WRITABLE_DIRECTORIES[@]}"; do
  chown -R www-data "${APP_HOME}/${DIR}"
done

# Retrieve configs if in QA or Prod
if [ "${Environment}" = 'qa' ] || [ "${Environment}" = 'prod' ]; then

  AWS_COMMAND='/usr/local/bin/aws'

  if [ -x "${AWS_COMMAND}" ]; then
    ${AWS_COMMAND} s3 cp --recursive s3://"${S3_CONFIG_LOCATION}"/configs/ "${APP_HOME}"/application/configs/
    find "${APP_HOME}/application/configs/" -type f -exec chmod 640 {} \;
    chgrp -R www-data "${APP_HOME}/application/configs/"
  else
    printf '%s\n' "awscli not found" && exit 1
  fi

else
  printf '%s\n' "TODO: copy local configs for dev"
fi

# Don't leave system config files in dangerous places
rm -rf /var/www/html/deploy

/usr/sbin/apache2ctl -k start -D FOREGROUND
