#!/bin/bash

PASS=$1
if [ $# -eq 0 ]
  then
    PASS="admin"
fi

. /etc/os-release 2&>1

### UPDATE ###
PORTAINER_PORT=9000
if [[ $NAME == *"EditShare"* ]]; then
PORTAINER_PORT=9001
fi
JWT=$(http --ignore-stdin POST :${PORTAINER_PORT}/api/auth Username="admin" Password="${PASS}" | jq -r ".jwt")
if [ "null" = "${JWT}" ]
then
    read -s -p "Please provide the password for the admin portainer account: `echo $'\n> '`" PASS </dev/tty
    echo
    JWT=$(http --ignore-stdin POST :${PORTAINER_PORT}/api/auth Username="admin" Password="${PASS}" | jq -r ".jwt")

    if [ "null" = "${JWT}" ]
    then
	echo "Invalid credentials for admin portainer account"
	exit 1;
    fi
fi

STACKS=$(http --ignore-stdin GET :${PORTAINER_PORT}/api/stacks "Authorization:Bearer ${JWT}")
for row in $(echo "${STACKS}" | jq -r '.[] | @base64'); do
    _jq() {
        echo ${row} | base64 --decode | jq -r ${1}
    }

    if [ $(_jq '.Name') = "MCC" ]; then
        STACK="$(_jq '.Id')"
    elif [ $(_jq '.Name') = "Helmut4" ]; then
        STACK="$(_jq '.Id')"
    fi
done

if test -z "${STACK}"
then
    echo "Helmut4 Stack not found - exiting.."
    exit 1;
fi


echo "Helmut4 Stack found with Id: ${STACK}"
CONTENT=$(http --ignore-stdin GET :${PORTAINER_PORT}/api/stacks/${STACK}/file "Authorization:Bearer ${JWT}" | jq -r ".StackFileContent")
BUFILE=/tmp/helmut4_stack_$(date +\%Y-\%m-\%d-\%H\%M\%S).yaml
echo ${CONTENT} > ${BUFILE}
echo "Created stack file backup: ${BUFILE}"

echo "Patching Helmut4 HouseKeeper" 

if [[ $CONTENT == *"repo.moovit24.de:443/mcp_hk"* ]]; then
	echo "Helmut HouseKeeper already found, skipped patch"
	exit 1;
else
CONTENT="$(cat << EndOfMessage
${CONTENT}

  hk:
     image: repo.moovit24.de:443/mcp_hk:4.0.2.3
     restart: always
     environment:
       parameters:
        --spring.data.mongodb.host=mongodb
        --spring.rabbitmq.host=rabbitmq
        --mcc.fx.url=http://fx:8100/v1/fx
        --mcc.co.url=http://co:8101/v1/co
        --mcc.io.url=http://io:8102/v1/io
        --mcc.users.url=http://users:8000/v1/members
        --mcc.stream.url=http://streams:8001/v1/streams
        --mcc.preference.url=http://preferences:8002/v1/preferences
        --mcc.metadata.url=http://metadata:8003/v1/metadata
        --mcc.logging.url=http://logging:8004/v1/logging/helmut
        --mcc.amqp.url=http://amqp:8005/v1/amqp/send
        --mcc.license.url=http://license:8006/v1/license
        --mcc.language.url=http://language:8007/v1/language
     volumes:
      - /etc/localtime:/etc/localtime:ro
     networks:
       - mcc
     depends_on:
       - mongodb
EndOfMessage
)"
fi

echo "Redeploying the Helmut Stack, this might take some time.. (Timeout is set to 10 minutes)"
http --ignore-stdin --timeout=1200 PUT ":${PORTAINER_PORT}/api/stacks/${STACK}?endpointId=1" "Authorization:Bearer ${JWT}" StackFileContent="${CONTENT}" Prune:=false
echo "Update done"
### /UPDATE ###
