#!/bin/bash
cat >/etc/motd <<EOL
   _____                               
  /  _  \ __________ _________   ____  
 /  /_\  \\\___   /  |  \_  __ \_/ __ \ 
/    |    \/    /|  |  /|  | \/\  ___/ 
\____|__  /_____ \____/ |__|    \___  >
        \/      \/                  \/ 
A P P   S E R V I C E   O N   L I N U X

Documentation : http://aka.ms/webapp-linux
PHP quickstart: https://aka.ms/php-qs
PHP version   : `php -v | head -n 1 | cut -d ' ' -f 2`
EOL

# Append Computer Name if set
if [ -n "$COMPUTERNAME" ]; then
  echo -e "Instance Name : $COMPUTERNAME" >> /etc/motd
fi

# Append Instance Id if set
if [ -n "$WEBSITE_INSTANCE_ID" ]; then
  echo -e "Instance Id   : $WEBSITE_INSTANCE_ID" >> /etc/motd
fi

echo -e "\nNote: Any data outside '/home' is not persisted"  >> /etc/motd

cat /etc/motd

# Copy default hosting start page to /home/site/wwwroot
cp /opt/startup/hostingstart.html /home/site/wwwroot/hostingstart.html

# if release.zip exists at /home/site/wwwroot, then move it to /home/site/deployments
if [ -f /home/site/wwwroot/release.zip ]; then
  mv /home/site/wwwroot/release.zip /home/site/deployments/release.zip 2>/dev/null || true
fi

# Get environment variables to show up in SSH session
# This will replace any \ (backslash), " (double quote), $ (dollar sign) and ` (back quote) symbol by its escaped character to not allow any bash substitution.
(printenv | sed -n "s/^\([^=]\+\)=\(.*\)$/export \1=\2/p" | sed 's/\\/\\\\/g' | sed 's/"/\\\"/g' | sed 's/\$/\\\$/g' | sed 's/`/\\`/g' | sed '/=/s//="/' | sed 's/$/"/' >> /etc/profile)

# starting sshd process
source /opt/startup/startssh.sh

# Install ca-certificates
source /opt/startup/install_ca_certs.sh

appPath="/home/site/wwwroot"
runFromPath="/tmp/webapp"
startupCommandPath="/opt/startup/startup.sh"
userStartupCommand="$@"
if [ -z "$userStartupCommand" ]
then
  userStartupCommand="php-fpm;";
else
  userStartupCommand="$userStartupCommand; php-fpm;"
fi

oryxArgs="create-script -appPath $appPath -output $startupCommandPath \
    -bindPort $PORT -startupCommand '$userStartupCommand'"

echo "Running oryx $oryxArgs"
eval oryx $oryxArgs
$startupCommandPath