#!/bin/bash

SNAPSHOT_VERSION="${1}"

if [ -z "${SNAPSHOT_VERSION}" ]
then
    echo "Error - please provide a snapshot"
    exit 1
fi

read -p "Please provide the username for the helmut updater: " USERNAME </dev/tty
echo
if [ -z "$USERNAME" ]; then
    echo "No username provided, using default: admin"
    USERNAME="admin"
fi

. /etc/os-release 2&>1

### SNAPSHOT ###
JWT=$(http --ignore-stdin POST :9000/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
    JWT=$(http --ignore-stdin POST :9000/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 :9000/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') == *"Helmut4"* ]] || [[ $(_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}"
echo "Grabbing snapshot '${SNAPSHOT_VERSION}' for Helmut4.." 
CONTENT=$(http --ignore-stdin GET :9000/api/stacks/${STACK}/file "Authorization:Bearer ${JWT}" | jq -r ".StackFileContent")
# Get Endpoint ID in case it isn't 1
ENDPOINT_ID=$(http --ignore-stdin GET :9000/api/endpoints "Authorization:Bearer ${JWT}" | jq ".[0].Id")
SNAPSHOT=$(http --ignore-stdin GET https://repo.moovit24.de/install/snapshots/${SNAPSHOT_VERSION})

if [ -z "${SNAPSHOT}" ]
then
    echo "Could not get snapshot ${SNAPSHOT_VERSION} from server"
    exit 1
elif [[ ${SNAPSHOT} == *"<html>"* ]]; then
    echo "Error grabbing snapshot ${SNAPSHOT_VERSION} from server:"
    echo "${SNAPSHOT}"
    exit 1
else
    echo "Snapshot ${SNAPSHOT_VERSION} has been loaded from server"
fi

echo "Check for migration"
# check target snapshot version
TARGET_SNAPSHOT=$(echo ${SNAPSHOT_VERSION} | sed 's/.*\([0-9]\{1,\}\.[0-9]\{1,\}\.[0-9]\{1,\}\).*/\1/' | cut -d '.' -f 2 | tr -d '.')
echo "Target snapshot version: ${TARGET_SNAPSHOT}"

# check current snapshot version by current license image
LICENSE_VERSION_RAW=$(docker ps | sed -n 's/.*\/mcc_license:\([^ ]*\).*/\1/p')

if [[ $LICENSE_VERSION_RAW == dev-* ]]; then
    LICENSE_VERSION="${LICENSE_VERSION_RAW:4:7}"
    echo "License version raw: ${LICENSE_VERSION}"
    LICENSE_VERSION=$(echo "${LICENSE_VERSION}" | cut -d '.' -f 2 | tr -d '.')
else
    LICENSE_VERSION=$(echo "${LICENSE_VERSION_RAW}" | cut -d '.' -f 2 | tr -d '.')
fi

echo "Current license version: ${LICENSE_VERSION}"
echo "Target snapshot version: ${TARGET_SNAPSHOT}"

if [[ ${TARGET_SNAPSHOT} -ge 8 && ${LICENSE_VERSION} -lt 8 ]] || [[ ${TARGET_SNAPSHOT} -lt 8 && ${LICENSE_VERSION} -ge 8 ]]; then
        echo -e "WARNING!!!\n\nYou try to update from a snapshot version < 4.8.0.0 which requires a license migration.\nYou need to contact moovit support to request a new one before we can continue as YOUR CURRENT LICENSE WILL BE DELETED DURING MIGRATION PROCESS.\n"
        read -s -p  "Do you want to continue? (yes/no) `echo $'\n> '`" RESP </dev/tty
        
        if [ "${RESP}" != "yes" ]
        then
            echo "Exiting..."
            exit 1
        fi

        MONGODB_VERSION=$(docker ps | sed -n 's/.*\/mcc_mongodb:\([^ ]*\).*/\1/p')
        MONGODB_CONTAINER_ID=$(docker ps | grep "repo.moovit24.de:443/mcc_mongodb:${MONGODB_VERSION}" | awk '{ print $1 }')
        if [ -z "${MONGODB_CONTAINER_ID}" ]
        then
            echo "Could not find container id for repo.moovit24.de:443/mcc_mongodb:${MONGODB_VERSION}"
            echo "Cluster? Trying with mcc_mongodbrs..."
            MONGODB_VERSION=$(docker ps | sed -n 's/.*\/mcc_mongodbrs:\([^ ]*\).*/\1/p')
            MONGODB_CONTAINER_ID=$(docker ps | grep "repo.moovit24.de:443/mcc_mongodbrs:${MONGODB_VERSION}" | awk '{ print $1 }')
            if [ -z "${MONGODB_CONTAINER_ID}" ]
            then
                echo "Could not find container id for repo.moovit24.de:443/mcc_mongodbrs:${MONGODB_VERSION}"
                echo "Exiting..."
                exit 1
            fi
        fi

        docker exec -t ${MONGODB_CONTAINER_ID} bash -c "mongo -u root -p bitte -authenticationDatabase=admin mcc_license --eval 'db.jWTDBO.drop()' && \ && echo"
else 
    echo "No migration required"
fi

echo -e "'bash:  : command not found' <- can be ignored."
for j in ${SNAPSHOT}    
do
    IFS=: read -r ENDPOINT ENDPOINT_VERSION <<< "$j"
#    OLD=$(echo "${CONTENT}" | sed -n "s/\/${ENDPOINT}:\([0-9]*\.[0-9]*\.[0-9]*\.[0-9]*\)/\/${ENDPOINT}:\1/p" | sed "s/image: repo.moovit24.de:443\/${ENDPOINT}://g" | awk '{$1=$1};1')
     OLD=$(echo "${CONTENT}" | sed -n "s/\/${ENDPOINT}:\(.*\)/\/${ENDPOINT}:\1/p" | sed "s/image: repo.moovit24.de:443\/${ENDPOINT}://g" | awk '{$1=$1};1')
    if ! [ -z "$OLD" ]
    then
#         CONTENT=$(echo "${CONTENT}" | sed "s/\/${ENDPOINT}:\([0-9]*\.[0-9]*\.[0-9]*\.[0-9]*\)/\/${ENDPOINT}:${ENDPOINT_VERSION}/g")
         CONTENT=$(echo "${CONTENT}" | sed "s/\/${ENDPOINT}:\(.*\)/\/${ENDPOINT}:${ENDPOINT_VERSION}/g")
         echo "Updated ${ENDPOINT}"
         echo "${OLD} -> ${ENDPOINT_VERSION}"
     fi
done

echo "Redeploying the Helmut Stack, this might take some time.. (Timeout is set to 10 minutes)"

http --ignore-stdin --timeout=1200 PUT ":9000/api/stacks/${STACK}?endpointId=${ENDPOINT_ID}" "Authorization:Bearer ${JWT}" StackFileContent="${CONTENT}" Prune:=false
mkdir -p /etc/helmut4 && chmod a+w /etc/helmut4
echo "${SNAPSHOT_VERSION}" > /etc/helmut4/helmut4.snapshot
echo "Update done"
### /SNAPSHOT ###
