#!/bin/bash

#judgement
if [[ -a /etc/supervisor/conf.d/supervisord.conf ]]; then
  exit 0
fi

#supervisor
cat > /etc/supervisor/conf.d/supervisord.conf <<EOF
[supervisord]
nodaemon=true

[program:rsyslog]
command=/usr/sbin/rsyslogd -n

[program:postgres]
command=/docker-entrypoint.sh postgres

[program:apache2]
command=/opt/apache2.sh

[program:pluto]
command=/usr/local/pluto/pluto.sh

[program:worker]
command=/usr/local/pluto/worker.sh

[program:r]
command=/opt/r_serv.sh

EOF

############
#  apache2
############
cat >> /opt/apache2.sh <<EOF
#!/bin/bash
#sed 's/coin-validator.local/'"$maildomain"'/' -i /etc/apache2/sites-available/000-default.conf

if [ ! -v $BASE_HREF ]; then
    sed -i 's|ProxyPass /API|ProxyPass /'"$BASE_HREF"'/API|g' /etc/apache2/sites-available/000-default.conf
    sed -i 's|ProxyPassReverse /API|ProxyPassReverse /'"$BASE_HREF"'/API|g' /etc/apache2/sites-available/000-default.conf
fi

# remove the apache2.pid to avoid apache starting failure after unclean shutdown
# similar issue to dive into the problem https://github.com/docker-library/php/issues/53
rm -f /var/run/apache2/apache2.pid
#echo "$(echo 'The rm -f /var/run/apache2/apache2.pid called. Date') $(`date`)" > /usr/local/pluto/apache2pidremoval.log
echo 'The command "rm -f /var/run/apache2/apache2.pid" called.' > /usr/local/pluto/apache2pidremoval.log
service apache2 start
tail -f /var/log/apache2/error.log
EOF
chmod +x /opt/apache2.sh

cat >> /opt/r_serv.sh <<EOF
#!/bin/bash

/usr/bin/R CMD Rserve --save 2>r.err >r.out
tail -f r.out

EOF
chmod +x /opt/r_serv.sh

##############
#  java pluto
##############
cat >> /usr/local/pluto/pluto.sh <<EOF
#!/bin/bash

if [ ! -v $IMAGE_VIEWER_URL ]; then
    if [ "$IMAGE_VIEWER_URL" != "-" ]; then
        sed -i "s|imageViewerApiUrl: 'http://localhost:80/'|imageViewerApiUrl: '""$IMAGE_VIEWER_URL""/'|g" /usr/local/pluto/front/main.bundle.js*
    fi
fi

echo $BASE_HREF

if [ ! -v $BASE_HREF ]; then
    if [ "$BASE_HREF" != "-" ]; then
        sed -i 's|basehref_docker|'"$BASE_HREF"'|g' /usr/local/pluto/front/index.html
        sed -i 's|basehref_docker|'"$BASE_HREF"'|g' /usr/local/pluto/front/main.bundle.js*
        sed -i "s|apiUrl: '/API/'|apiUrl: '/""$BASE_HREF""/API/'|g" /usr/local/pluto/front/main.bundle.js*
    fi
    if [ "$BASE_HREF" == "-" ]; then
        sed -i 's|basehref_docker||g' /usr/local/pluto/front/index.html
        sed -i 's|basehref_docker||g' /usr/local/pluto/front/main.bundle.js*
    fi
fi

java -cp Pluto.jar:conf com.nanostring.pluto.Main 2>/dev/null >/dev/null
EOF
chmod +x /usr/local/pluto/pluto.sh

cat >> /usr/local/pluto/worker.sh <<EOF
#!/bin/bash
java -cp worker.jar com.nanostring.pluto.scriptworker.Main 2>/dev/null >/dev/null
EOF
chmod +x /usr/local/pluto/worker.sh
