#!/bin/bash

# Retrieve configs if in QA or Prod
if [ "${Environment}" = 'qa' ] || [ "${Environment}" = 'prod' ]; then
  AWS_COMMAND=$(whereis aws | cut -d ' ' -f 2)

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

# Munge some files that are hard-coded. If this app were deployed with any regularity, we would fix it upstream, but it's not.
if [ "${Environment}" = 'qa' ]; then
  sed -i 's@webservice.theorchard.com@webservice.qaorch.com@g' "${APP_HOME}/public/webservices/direct_delivery.wsdl"
  sed -i 's@webservice.theorchard.com@webservice.qaorch.com@g' "${APP_HOME}/public/webservices/sp_direct_delivery.php"
fi

# Copy htaccess file into correct directory
cp -a "${APP_HOME}/deploy/.htaccess" "${APP_HOME}/public/.htaccess"

# Don't leave system config files in dangerous places
rm -rf "${APP_HOME}/deploy"

/usr/sbin/httpd -D FOREGROUND
