#!/bin/bash

read -d '' runner <<'EOF'
#!/bin/bash

set -e
export HOME=/app
hash -r
cd \$HOME

cat << CONF > supervisord.conf
[supervisord]
loglevel=debug
nodaemon=true
CONF

while read line
do
  if [[ "\$line" =~ ^([A-Za-z0-9_-]+):\s*(.+)$ ]]
  then
    name=\${line%%:*}
    command=\${line#*: }
    cat << CONF >> supervisord.conf
[program:\${name}]
command=/exec sh -c '\${command}'
autostart=true
autorestart=true
stopsignal=QUIT

CONF
  fi
done < "Procfile"



supervisord -c supervisord.conf
EOF

source "$(dirname $0)/../dokku_common"

verify_app_name "$1"

# Check for Procfile
if ! docker run --entrypoint="/bin/bash" --rm "$IMAGE" -c "[[ -f /exec ]] && [[ -f /app/Procfile ]]"; then
  exit 0
fi

echo "-----> Injecting Supervisor ..."

CMD="cat > /start && \
  dpkg -s supervisor > /dev/null 2>&1 || \
  (apt-get update && apt-get install -y supervisor && apt-get clean)"

echo "$runner" | docker run -i -a stdin $IMAGE /bin/bash -c "$CMD" | attach_and_commit_image "$IMAGE"
