#!/usr/local/bin/bash

# Copyright (c) Inform Systems Group LLC by Alexey Ignatev, www.isg.dev
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.

# Update just bin Polkadot version 1.1.4

SRC_DIR="/usr/local/polkadot-sdk"
LOG="/var/log/update_dot.log"
SERVICE_NAME="polkadot" # name for command: service $SERV_NAME stop and start
NEWSERVICE_DIR="${SRC_DIR}/target/release"
OLDSERVICE_DIR="/usr/local/bin"
STOP_TIMEOUT="300"
POLKADOT_BINS="polkadot polkadot-execute-worker polkadot-prepare-worker polkadot-omni-node polkadot-parachain substrate-node"

send_log() {
    echo `date "+%Y.%m.%d %H:%M:%S"` ${1} >>${LOG}
    echo `date "+%Y.%m.%d %H:%M:%S"` ${1}
}

if [ -d "${SRC_DIR}" ]; then
    cd ${SRC_DIR}
else 
    send_log "Directory ${SRC_DIR} with sources NOT FOUND! Exiting"
    exit 1
fi

if [ ! -x "${OLDSERVICE_DIR}/${SERVICE_NAME}" ]; then
    send_log "Service binary: ${OLDSERVICE_DIR}/${SERVICE_NAME} NOT FOUND! Exiting"
    exit 1
fi

#cheking version
BIN_VER="v`${OLDSERVICE_DIR}/${SERVICE_NAME} -V | head -1 | awk '{print $2}' | awk 'BEGIN{FS=OFS="-"}{NF--; print}'`"
#SRC_VER="`git tag -l | sort -V | grep -v -- '-rc' |tail -1 |awk -F"polkadot-" '{print $2}'`"
SRC_VER="v`git tag -l | sort -V | grep -v -- '-rc' | grep "polkadot-" | tail -1 | awk -F"v" 'BEGIN{OFS="v";} {print $2;}'`"
SUMVER_BIN="`echo ${BIN_VER}| tr -d 'v.-'`"
SUMVER_SRC="`echo ${SRC_VER}| tr -d 'v.-'`"

if [ "${BIN_VER}" = "${SRC_VER}" ] && [ ! "$1" =  "force" ]; then
    send_log "Binary version: ${BIN_VER}, source version is ${SRC_VER}. Version is same, skipping update"
    exit 0
elif [ ! "${SUMVER_BIN}" -lt "${SUMVER_SRC}" ] && [ ! "$1" =  "force" ]; then
    send_log "Binary version: ${BIN_VER}, sum: ${SUMVER_BIN}, source version is ${SRC_VER},sum: ${SUMVER_SRC}. Unknown situation, update skipping! Exiting"
    exit 1
fi

# updating 
send_log "Binary version: ${BIN_VER}, source version is ${SRC_VER}. Starting update procedure"


NEWBIN_VER="v`${NEWSERVICE_DIR}/${SERVICE_NAME} -V | head -1 | awk '{print $2}' | awk 'BEGIN{FS=OFS="-"}{NF--; print}'`"
SUMNEWVER_BIN="`echo ${NEWBIN_VER}| tr -d 'v.'`"

if [ ! "${NEWBIN_VER}" = "${SRC_VER}" ] && [ ! "$1" =  "force" ]; then
    send_log "NEW ${SERVICE_NAME} binary version: ${NEWBIN_VER}, and SOURCE version: ${SRC_VER} mismach! Exiting"
    exit 1
fi

if [ ! "${SUMVER_BIN}" -lt "${SUMNEWVER_BIN}" ] && [ ! "$1" =  "force" ]; then
    send_log "NEW ${SERVICE_NAME} binary version summ: ${SUMNEWVER_BIN}, running binary version summ: ${SUMVER_BIN}. Unknown error! Exiting"
    exit 1
fi

# stopping running version
DOT_PID="`cat /var/run/${SERVICE_NAME}.pid`"

send_log "Stopping polkadot service with PID: ${DOT_PID}"
service ${SERVICE_NAME} stop >>${LOG} 2>&1

STOP_COUNT="0"
send_log "Start waiting for pid "${DOT_PID}" successful stopped (timeout seconds: ${STOP_TIMEOUT})"
while ps -A | grep "${DOT_PID}" |grep -v "grep ${DOT_PID}"; do
    if [ "${STOP_COUNT}" -gt "${STOP_TIMEOUT}" ]; then
        send_log "Stopping ${SERVICE_NAME} TIMEOUT! Exiting..."
        exit 1
    else
        send_log "Waiting for ${SERVICE_NAME} successful stopped... (${STOP_COUNT} seconds...)"
        sleep 1
    fi
    STOP_COUNT=$((${STOP_COUNT} + 1 ))
done

sleep 5

# backup
for BIN in ${POLKADOT_BINS}; do
    if [ -x "${OLDSERVICE_DIR}/${BIN}" ]; then
        send_log "Backing up old binary: ${OLDSERVICE_DIR}/${BIN}"
        mv -f ${OLDSERVICE_DIR}/${BIN} ${OLDSERVICE_DIR}/${BIN}.old >>${LOG} 2>&1
    else
        send_log "Binary:${OLDSERVICE_DIR}/${BIN} NOT FOUND! Exiting"
        exit 1
    fi
done

# replace
for BIN in ${POLKADOT_BINS}; do
    if [ -x "${NEWSERVICE_DIR}/${BIN}" ]; then
        send_log "Stripping and copying new binary: ${NEWSERVICE_DIR}/${BIN}"
        strip ${NEWSERVICE_DIR}/${BIN}
        cp -f ${NEWSERVICE_DIR}/${BIN} ${OLDSERVICE_DIR}/${BIN} >>${LOG} 2>&1
    else
        send_log "Binary:${NEWSERVICE_DIR}/${BIN} NOT FOUND! Exiting"
        exit 1
    fi
done

service ${SERVICE_NAME} start >>${LOG} 2>&1
if [ "$?" = "0" ]; then
    send_log "Starting new ${SERVICE_NAME} binary successful, update complete"
else
    send_log "Starting new ${SERVICE_NAME} binary ERROR! Exiting"
fi
