#!/bin/bash

# sample .env.local:
#
#APP_ENV=preprod
#APP_ENV_NAME=preprod
#APP_DOMAIN=https://mysite.preprod-gda.fr
#
# default deployed branch is develop, use DEFAULT_DEPLOY_BRANCH if you want to change the branch,
# ex: DEFAULT_DEPLOY_BRANCH=master

set -e


CURRENTDIR=$(pwd)
BASEDIR=$(dirname $0)
ABSPATH=$(readlink -f $0)
ABSDIR=$(dirname $ABSPATH)

APP_ENV="none"
if [ -f .env.local ]; then
  APP_ENV=$(cat .env.local | grep ^APP_ENV= | sed -E 's|^(.+)=(.*)$|\2|g' | tr -d '\011\012\013\014\015\040' | xargs)
fi

APP_ENV_NAME="--"
if [ -f .env.local ]; then
  APP_ENV_NAME=$(cat .env.local | grep ^APP_ENV_NAME= | sed -E 's|^(.+)=(.*)$|\2|g' | tr -d '\011\012\013\014\015\040' | xargs)
fi

APP_DOMAIN="none"
if [ -f .env.local ]; then
  APP_DOMAIN=$(cat .env.local | grep ^APP_DOMAIN= | sed -E 's|^(.+)=(.*)$|\2|g' | tr -d '\011\012\013\014\015\040' | xargs)
else
  APP_DOMAIN='no domain provided'
fi

DEFAULT_BRANCH="develop"
if [ -f .env.local ] && [ $(cat .env.local | grep ^DEFAULT_DEPLOY_BRANCH) ];
then
  DEFAULT_BRANCH=$(cat .env.local | grep ^DEFAULT_DEPLOY_BRANCH= | sed -E 's|^(.+)=(.*)$|\2|g' | tr -d '\011\012\013\014\015\040' | xargs)
else
  DEFAULT_BRANCH="develop"
fi

SLACK_MSG_URL=""


cd $ABSDIR
echo "
[deploy.sh: deploy install] $(date +"%Y-%m-%d-%H:%M:%S")
"

#read -p "Specify branch to deploy [$DEFAULT_BRANCH]: " BRANCH
BRANCH=${BRANCH:-$DEFAULT_BRANCH}


#git status

echo # new line
echo # new line

#read -p "Branch 'origin/$BRANCH' will be deployed on app env '$APP_ENV', do you want to proceed ? [y/N]" CONFIRMED
#CONFIRMED=${CONFIRMED:-N}
#echo # new line

# /!\ overwrite confirmation
CONFIRMED='Y'
# /!\ overwrite confirmation

if [[ $CONFIRMED =~ ^([Yy])$ ]]
then
#    git fetch origin $BRANCH
#    git reset --hard origin/$BRANCH

    # remove cache before any php-related action, as code signature may have changed after pull
#    php bin/console ca:cl
    rm -rf ./var/cache

    if [ "$APP_ENV" = "dev" ]; then
      composer install
    else
      composer install --no-dev --optimize-autoloader
    fi

    php bin/console do:mi:mi --no-interaction
    php bin/console ass:inst --symlink
    php bin/console gda:cache-suffix:refresh
#    php bin/console ca:cl
    php bin/console ca:wa

    #git log -n 1

    echo "

    ---------------------------------------
    Sending slack message."
    # escape message using several vars
    SLACK_MSG="*[${APP_ENV_NAME}]* Deploy success for branch *${BRANCH}* (app env *$APP_ENV*) ${APP_DOMAIN} :proo: :animated_pigeon: :party_blob:"
    TEXT=$(echo "$SLACK_MSG" | sed 's/"/\"/g' | sed "s/'/\'/g")
    JSON_STR="{\"text\": \"$TEXT\"}"
    SLACK_WEBM=""

    curl -s -d "payload=$JSON_STR" "$SLACK_MSG_URL"
    curl -s -d "payload=$JSON_STR" "$SLACK_WEBM"

    echo "

    Deployment successful.
    "
else
    echo "

    Deployment aborted - was not confirmed.
    "
fi

cd $CURRENTDIR

