#!/bin/sh
#set -x

LOG="/var/log/scripts/rsync_polkadot.log"
#DOTPATH="/mnt/data/jails"

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

if [ "$1" = "" ]; then
    send_log "Please enter: ${0} local /mnt/data/jails/ksm /mnt/data/jails/dot   - for local update "
    send_log "Please enter: ${0} remote root@gw3:/mnt/data/jails/dot /mnt/data/jails/ksm   - for remote update "
    exit 0
else
    sync_type="${1}"
fi

if [ "$2" = "" ]; then
    send_log "Please enter: ./rsync_polkadot.sh local /mnt/data/jails/ksm /mnt/data/jails/dot   - for local update "
    send_log "Please enter: ./rsync_polkadot.sh remote root@gw3:/mnt/data/jails/dot /mnt/data/jails/ksm   - for remote update "
    exit 0
else
    sync_from="${2}"
fi

if [ "$3" = "" ]; then
    send_log "Please enter: ./rsync_polkadot.sh local /mnt/data/jails/ksm /mnt/data/jails/dot   - for local update "
    send_log "Please enter: ./rsync_polkadot.sh remote root@gw3:/mnt/data/jails/dot /mnt/data/jails/ksm   - for remote update "
    exit 0
else
    sync_to="${3}"
fi



JAIL_TEST_TO="`jls | grep ${sync_to} | awk '{print $3}'`"

if [ -z "$JAIL_TEST_TO" ]; then
    send_log "Cheking jail name for destination sync (${sync_to}) ERROR! Exiting..."
    exit 1
fi

if [ "${sync_type}" = "remote" ]; then
    send_log "Checking version of polkadot binary from remote ${sync_from}"
    FROM_ADDR="`echo ${sync_from} | awk -F':' '{print $1}'`"
    FROM_PATH="`echo ${sync_from} | awk -F':' '{print $2}'`"
    VER_FROM_ORIG="`ssh -i /mnt/data/keys/unison.key -p 7832 ${FROM_ADDR} "${FROM_PATH}/usr/local/bin/polkadot -V" | head -1 | awk '{print $2}' | awk 'BEGIN{FS=OFS="-"}{NF--; print}'`"
    echo $VER_FROM_ORIG
    if [ -n "${VER_FROM_ORIG}" ]; then
	VER_FROM="v${VER_FROM_ORIG}"
    else
	send_log "Cheking version of polkadot binary from remote (${sync_from}) ERROR! Exiting..."
        exit 1
    fi
elif [ "${sync_type}" = "local" ]; then

    JAIL_TEST_FROM=`jls | grep ${sync_from} | awk '{print $3}'`
    if [ -z "$JAIL_TEST_FROM" ]; then
	send_log "Cheking jail name for source sync (${sync_from}) ERROR! Exiting..."
	exit 1
    fi
    
    send_log "Checking version of polkadot binary from local ${sync_from}"
    VER_FROM="v`${sync_from}/usr/local/bin/polkadot -V | head -1 | awk '{print $2}' | awk 'BEGIN{FS=OFS="-"}{NF--; print}'`"
else
    send_log "Only local and remote update supported, exiting"
    exit 0
fi

#echo ${VER_FROM}
VER_TO_ORIG="`${sync_to}/usr/local/bin/polkadot -V | head -1 | awk '{print $2}' | awk 'BEGIN{FS=OFS="-"}{NF--; print}'`"
if [ -n "${VER_TO_ORIG}" ]; then
    VER_TO="v${VER_TO_ORIG}"
else
    send_log "Cheking version of local polkadot binary (${sync_to}) ERROR! Exiting..."
    exit 1
fi

SUMVER_FROM="`echo ${VER_FROM}| tr -d 'v.-'`"
SUMVER_TO="`echo ${VER_TO}| tr -d 'v.-'`"
#echo ${SUMVER_FROM}
#echo ${SUMVER_TO}

if [ "${SUMVER_FROM}" -gt "${SUMVER_TO}" ] || [ "$4" = "force" ]; then
    send_log "Source version: ${VER_FROM}, destination version is ${VER_TO}. Starting update procedure"
else
    send_log "Source version: ${VER_FROM}, destination version is ${VER_TO}. Skipping update"
    exit 0
fi

DISK=`zfs list | grep "${sync_to}" | head -1 | awk '{print $1}' | awk -F'/' '{print $1}'`

if [ -z "${DISK}" ]; then
    send_log "Cheking disk name for destination sync (${sync_to}) ERROR! Exiting..."
    exit 1
fi

ZFS_TO=`echo ${sync_to} | sed  "s/\/mnt/${DISK}/g"`
if zfs list |grep ${ZFS_TO}_temp; then
    send_log "Found existing ${ZFS_TO}_temp! Exiting..."
    exit 1
fi

if zfs list |grep ${ZFS_TO}_old; then
    send_log "Found existing ${ZFS_TO}_old! Destroying..."
    zfs destroy ${ZFS_TO}_old >>${LOG} 2>&1
#    exit 1
fi

SNAP_NAME=`date "+%Y-%m-%d_%H:%M:%S"`
zfs snap ${ZFS_TO}@${SNAP_NAME} >>${LOG} 2>&1
if [ "$?" = "0" ]; then
    send_log "ZFS snap ${ZFS_TO}@${SNAP_NAME} successful completed"
else
    send_log "ZFS snap ${ZFS_TO}@${SNAP_NAME} ERROR! Exiting..."
    exit 1
fi

zfs clone ${ZFS_TO}@${SNAP_NAME} ${ZFS_TO}_temp >>${LOG} 2>&1
if [ "$?" = "0" ]; then
    send_log "ZFS clone ${ZFS_TO}@${SNAP_NAME} to ${ZFS_TO}_temp successful completed"
else
    send_log "ZFS clone ${ZFS_TO}@${SNAP_NAME} to ${ZFS_TO}_temp ERROR! Exiting..."
    exit 1
fi

if [ "${sync_type}" = "remote" ]; then
    sync_parm="ssh -p 7832 -i /mnt/data/keys/unison.key"
elif [ "${sync_type}" = "local" ]; then

    JAIL_FROM=`jls | grep ${sync_from} | awk '{print $3}'`
    if [ ! -z "$JAIL_FROM" ]; then
	send_log "Selecting jail name (${JAIL_FROM}) successful completed"
    else
	send_log "Selecting jail name by path (${sync_from}) ERROR! Exiting..."
	exit 1
    fi

    send_log "Running cargo clean for polkadot sources in jail ${JAIL_FROM}"
#    jexec ${JAIL_FROM} cd /usr/local/polkadot-sdk && /usr/local/bin/cargo clean & >>${LOG} 2>&1
    jexec ${JAIL_FROM} /usr/local/etc/scripts/cargo_clean.sh  >>${LOG} 2>&1
    sync_parm=""
else
    send_log "Only local and remote update supported, exiting"
    exit 0
fi

if [ "${sync_type}" = "remote" ]; then
    send_log "Starting remote sync with sync parm: ${sync_parm} from ${sync_from} to ${sync_to}_temp"
    #--bwlimit=5M
    rsync -e "${sync_parm}" --progress -avHz \
    --exclude="/tmp" \
    --exclude="/mnt" \
    --exclude="/dev" \
    --exclude="/var/log" \
    --exclude="/var/run" \
    --exclude="/var/spool" \
    --exclude="/etc/resolv.conf" \
    --exclude="/etc/rc.conf" \
    --exclude="/etc/crontab" \
    --exclude="/etc/fstab" \
    --exclude="/root/.bash_history" \
    --exclude="/root/.history" \
    --exclude="/root/.local/share" \
    --exclude="*.core" \
    --exclude="/usr/local/bin/polkadot" \
    --exclude="/usr/local/bin/polkadot-execute-worker" \
    --exclude="/usr/local/bin/polkadot-prepare-worker" \
    --exclude="/usr/local/bin/polkadot-omni-node" \
    --exclude="/usr/local/bin/polkadot-parachain" \
    --exclude="/usr/local/bin/substrate-node" \
    --numeric-ids --delete --delete-after --suffix=_`date "+%Y-%m-%d.%H:%M:%S"` ${sync_from}/ ${sync_to}_temp >>${LOG} 2>&1

    if [ "$?" = "0" ]; then
	send_log "Remote sync from ${sync_from} to ${sync_to} successful completed"
    else
	send_log "Remote sync from ${sync_from} to ${sync_to} ERROR! Exiting..."
	exit 1
    fi
elif [ "${sync_type}" = "local" ]; then
    send_log "Starting local sync with sync parm: ${sync_parm} from ${sync_from} to ${sync_to}_temp"
    # --bwlimit=10M 
    rsync -e "${sync_parm}" --progress -avHz \
    --exclude="/tmp" \
    --exclude="/mnt" \
    --exclude="/dev" \
    --exclude="/var/log" \
    --exclude="/var/run" \
    --exclude="/var/spool" \
    --exclude="/etc/resolv.conf" \
    --exclude="/etc/rc.conf" \
    --exclude="/etc/crontab" \
    --exclude="/etc/fstab" \
    --exclude="/root/.bash_history" \
    --exclude="/root/.history" \
    --exclude="/root/.local/share" \
    --exclude="*.core" \
    --numeric-ids --delete --delete-after --suffix=_`date "+%Y-%m-%d.%H:%M:%S"` ${sync_from}/ ${sync_to}_temp >>${LOG} 2>&1

    if [ "$?" = "0" ]; then
	send_log "Local sync from ${sync_from} to ${sync_to} successful completed"
    else
	send_log "Local sync from ${sync_from} to ${sync_to} ERROR! Exiting..."
	exit 1
    fi
else
    send_log "Only local and remote sync supported, exiting"
    exit 0
fi


JAIL_TO=`jls | grep ${sync_to} | awk '{print $3}'`
if [ ! -z "$JAIL_TO" ]; then
    send_log "Selecting jail name (${JAIL_TO}) successful completed"
else
    send_log "Selecting jail name by path (${sync_to}) ERROR! Exiting..."
    exit 1
fi

service jail stop ${JAIL_TO}
if [ "$?" = "0" ]; then
    send_log "Stopping ${JAIL_TO} successful completed"
else
    send_log "Stopping ${JAIL_TO} ERROR! Exiting..."
    exit 1
fi

zfs promote ${ZFS_TO}_temp >>${LOG} 2>&1
if [ "$?" = "0" ]; then
    send_log "ZFS promote ${ZFS_TO}_temp successful completed"
else
    send_log "ZFS promote ${ZFS_TO}_temp ERROR! Exiting..."
    exit 1
fi

zfs umount -f ${ZFS_TO} >>${LOG} 2>&1
if [ "$?" = "0" ]; then
    send_log "ZFS umount ${ZFS_TO}_temp successful completed"
else
    send_log "ZFS umount ${ZFS_TO}_temp ERROR! Exiting..."
    exit 1
fi

zfs rename ${ZFS_TO} ${ZFS_TO}_old >>${LOG} 2>&1
if [ "$?" = "0" ]; then
    send_log "ZFS rename ${ZFS_TO} to ${ZFS_TO}_old successful completed"
else
    send_log "ZFS rename ${ZFS_TO} to ${ZFS_TO}_old ERROR! Exiting..."
    exit 1
fi

zfs rename ${ZFS_TO}_temp ${ZFS_TO} >>${LOG} 2>&1
if [ "$?" = "0" ]; then
    send_log "ZFS rename ${ZFS_TO}_temp to ${ZFS_TO} successful completed"
else
    send_log "ZFS rename ${ZFS_TO}_temp to ${ZFS_TO} ERROR! Exiting..."
    exit 1
fi

service jail start ${JAIL_TO}
if [ "$?" = "0" ]; then
    send_log "Starting ${JAIL_TO} successful completed"
else
    send_log "Starting ${JAIL_TO} ERROR! Exiting..."
    exit 1
fi

if [ "${sync_type}" = "remote" ]; then
    send_log "Running force polkadot service compilation"
    jexec ${JAIL_TO} /usr/local/bin/bash /usr/local/etc/scripts/recompile_and_update.sh &  >>${LOG} 2>&1
fi

