#!/bin/bash

SNAPSHOT_VERSION="${1}"

if [ -z "${SNAPSHOT_VERSION}" ]
then
    echo "Error - please provide a snapshot"
    exit 1
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")
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 1-3 | tr -d '.')

if [[ ${TARGET_SNAPSHOT} -ge 480 ]]; then
   # check current snapshot version by current license image
    LICENSE_VERSION=$(docker ps | sed -n 's/.*\/mcc_license:\([^ ]*\).*/\1/p')
    if [[ ! "${LICENSE_VERSION}" =~ ^[0-9.]+$ ]]; then
        echo "Invalid current snapshot version: ${LICENSE_VERSION}"
        exit 1
    fi
    LICENSE_VERSION=$(echo "${LICENSE_VERSION}" | cut -d '.' -f 1-3 | tr -d '.')

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

    if [[ ${LICENSE_VERSION} -lt 480 ]]; 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}"
            exit 1
        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
else 
    echo "No migration required"
fi

echo -e "'bash:  : command not found' <- can be ignored. If you see '...MongoDB server version: 3.4.19\ntrue'\n deletion was successful."
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=1" "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 ###
