#!/bin/bash

SHARED_MOUNT_DIRECTORIES=('appScreenShots' 'artist' 'release' 'vendor')
# APP_HOME is provided by the Dockerfile and EFS_VOLUME_CONTAINER_PATH is provided by the Docker runtime (e.g. Fargate)

# Add directories used for different types of images. If EFS volume is specified, symlink to existing image directories.
# These should be backed by shared storage across all images hosts, so test for EFS_VOLUME_CONTAINER_PATH.
for DIR in "${SHARED_MOUNT_DIRECTORIES[@]}"; do
  if [ ! -d "${APP_HOME}/${DIR}" ]; then
    if [ -d "${EFS_VOLUME_CONTAINER_PATH}" ]; then
      # Each shared directory should be individually stubbed out in the shared volume and owned by apache
      if [ ! -d "${EFS_VOLUME_CONTAINER_PATH}/${DIR}" ]; then
        printf '%s\n' "Creating ${EFS_VOLUME_CONTAINER_PATH}/${DIR} as apache user"
        su -s /bin/bash apache -c "mkdir -p ${EFS_VOLUME_CONTAINER_PATH}/${DIR}"
      fi
      ln -s "${EFS_VOLUME_CONTAINER_PATH}/${DIR}" "${APP_HOME}/${DIR}"
      printf '%s\n' "Linked ${APP_HOME}/${DIR} to ${EFS_VOLUME_CONTAINER_PATH}/${DIR}"
    else
      mkdir -p "${APP_HOME}/${DIR}"
      chown apache "${APP_HOME}/${DIR}"
    fi
  else
    printf '%s\n' "Directory already exists: ${APP_HOME}/${DIR}"
    if [ -L "${APP_HOME}/${DIR}" ] && [ -e "${APP_HOME}/${DIR}" ]; then
      printf '%s\n' "${APP_HOME}/${DIR} is a working symlink"
      printf '%s\n' "Directory: $(ls -l "${APP_HOME}/${DIR}")"
    fi
  fi
done

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

/usr/sbin/httpd -D FOREGROUND
