#!/bin/bash

set -e

shopt -s dotglob
echo "---> Installing application source ..."
mv /tmp/src/* ./

if [ -d ./cfg ]; then
  echo "---> Copying configuration files..."
  if [ "$(ls -A ./cfg/*.conf)" ]; then
    cp -v ./cfg/*.conf /opt/app-root/etc/httpd.d/
  fi
fi

# Allow for http proxy to be specified in uppercase
if [[ -n "${HTTP_PROXY:-}" && -z "${http_proxy:-}" ]]; then
  export http_proxy=$HTTP_PROXY
fi

export CPAN_MIRROR=${CPAN_MIRROR:-""}

MIRROR_ARGS=""

if [ -n "$CPAN_MIRROR" ]; then
  MIRROR_ARGS="--mirror $CPAN_MIRROR"
fi

# Don't test installed Perl modules by default
if [ "${ENABLE_CPAN_TEST}" = true ]; then
  export ENABLE_CPAN_TEST=""
else
  export ENABLE_CPAN_TEST="--notest"
fi

# Configure mod_perl for PSGI.
# If PSGI_FILE variable is set but empty, skip it.
# If PSGI_FILE is set and non-empty, use it.
# If PSGI_FILE does not exist, check if exactly one ./*.psgi file exists and
# use that file.
# If PSGI_URI_PATH variable has a value, use it as a location. Default is "/".
if [ ! -v PSGI_FILE ]; then
    PSGI_FILE=$(find -maxdepth 1 -name '*.psgi' -type f)
fi
PSGI_FILE_NUMBER=$(printf '%s' "$PSGI_FILE" | wc -l)
if [ -n "$PSGI_FILE" -a "$PSGI_FILE_NUMBER" -eq 0 ]; then
    echo "---> PSGI application found in $PSGI_FILE"
    cat >> cpanfile <<"EOF"
requires 'Plack::Handler::Apache2';
EOF
    # XXX: Escape PSGI_FILE value against httpd control characters
    PSGI_FILE=$(printf '%s' "$PSGI_FILE" | sed -e 's/\\/\\\\/g' -e 's/"/\\"/g')
    cat > /opt/app-root/etc/httpd.d/40-psgi.conf <<EOF
<Location ${PSGI_URI_PATH:=/}>
    SetHandler perl-script
    PerlResponseHandler Plack::Handler::Apache2
    PerlSetVar psgi_app "$PSGI_FILE"
</Location>
EOF
elif [ "$PSGI_FILE_NUMBER" -gt 0 ]; then
    echo "---> Multiple PSGI applications found:"
    printf '%s' "$PSGI_FILE"
    echo "---> Skipping PSGI autoconfiguration!"
fi

# Installing dependencies with cpanfile
if [ -f "cpanfile" ]; then
  echo "---> Installing modules from cpanfile ..."
  cpanm $MIRROR_ARGS $ENABLE_CPAN_TEST -l extlib Module::CoreList
  cpanm $MIRROR_ARGS $ENABLE_CPAN_TEST -l extlib --installdeps .
else
  echo "---> No cpanfile found, nothing to install"
fi

# Fix source directory permissions
fix-permissions ./
