#!/bin/bash

################################################################################################################
###
###  This script rollback data and logs to a backup point in time.
###  The backup point can be select from the backup plan from LOCAL_BACKUP_PLAN $JAGUAR_HOME/conf/server.conf
###  This script will list the options available for user to choose.
###
###  JaguarDB server will shortly stop and start after the quick rollback process.
###
###  You must be the owner of the JaguarDB server process to run this script.
###
################################################################################################################

function copyfiles
{
    src=$1
    dst=$2

    mkdir -p "$dst"
    find "$src" -mindepth 1 -maxdepth 1 -exec /bin/cp -a -f -t "$dst" {} +
}

function movefiles
{
    src=$1
    dst=$2

    mkdir -p "$dst"
    find "$src" -mindepth 1 -maxdepth 1 -exec /bin/mv -f -t "$dst" {} +
}



###################################### main #########################################
shopt -s extglob


me=`whoami`

if [[ "x$me" = "xroot" ]]; then
    echo "You cannot run as root or sudo. Run the script as the JaguarDB owner."
    exit 1
fi

if [[ -f "$HOME/.jaguarhome" ]]; then
    JAGUAR_HOME=$(cat "$HOME/.jaguarhome")
else
    JAGUAR_HOME="$HOME"
fi

if [[ -z $JAGUAR_HOME ]]; then
    echo "JAGUAR_HOME is empty, quit"
    exit 10
fi

if [[ "x$JAGUAR_HOME" = "x/" ]]; then
    echo "JAGUAR_HOME is /, quit"
    exit 20
fi


jagowner=`stat -c '%U' $JAGUAR_HOME`
if [[ "x$me" = "x$jagowner" ]]; then
    echo "OK, you are the owner of $JAGUAR_HOME"
else
    echo "!!! You are not the owner of $JAGUAR_HOME  Quit now"
    exit 1
fi


plan=`grep LOCAL_BACKUP_PLAN $JAGUAR_HOME/conf/server.conf |grep -v '#'`
# LOCAL_BACKUP_PLAN=15MIN:OVERWRITE|HOURLY:OVERWRITE|DAILY:OVERWRITE|WEEKLY:OVERWRITE|MONTHLY:OVERWRITE

periods=`echo $plan|cut -d'=' -f2`
DATAABAN="data.abandoned"
LOGABAN="log.abandoned"

declare -A mymap

((selnum=1))
echo
echo "The system has the following backups:"
echo
IFS='|' read -ra items <<< "$periods"
selpolicy="SNAPSHOT"
for item in "${items[@]}"
do
    lower=${item,,}

    ### hourly daily ..
    tm=`echo $lower|cut -d':' -f1`
    policy=`echo $item|cut -d':' -f2`

    ### OVERWRITE or SNAPSHOT
    if [[ "x$policy" = "xOVERWRITE" ]]; then
        echo "$tm copy:"
        modtime=`date -u -d @$(stat -c '%Y' $JAGUAR_HOME/backup/$tm/main/system/TableSchema.hdb)`
        echo -e "$selnum  $tm\t\t(update time: $modtime)"
        val="$tm:overwrite"
        mymap["$selnum"]="$val"
        ((selnum=selnum+1))
     elif [[ "x$policy" = "xSNAPSHOT" ]]; then
        ### list $JAGUAR_HOME/backup/$tm/2026-*
        echo "$tm snapshots:"
        snapshots=`/bin/ls -d $JAGUAR_HOME/backup/$tm/2[0-9][0-9][0-9]-[0-9][0-9]-* 2>/dev/null`

        ((cnt=0))
        for s in $snapshots; do
            sn=`basename $s`
            echo -e "$selnum\tsnapshot $sn"
            val="$tm:snapshot:$sn"
            mymap["$selnum"]="$val"
            ((selnum=selnum+1))
            ((cnt=cnt+1))
        done

        if ((cnt < 1)); then
            echo "No snapshots"
        fi
     else
        echo "$tm  has invalid backup policy ($policy) (not OVERWRITE not SNAPSHOT)"
     fi
     echo
done

echo

while true
do
    echo -n "Select a number from the above entries: (0) to quit: "
    read entry
    if ((entry==0)); then
        exit 0
    fi

    seltmdesc=${mymap["$entry"]}
    if [[ -z "$seltmdesc" ]]; then
        continue
    fi

    echo "OK, you selected number $entry for $seltmdesc"
    break
done


### seltmdesc:
## daily:overwrite
## hourly:snapshot:2026-06-08-11-42-ssd
seltm=`echo $seltmdesc|cut -d: -f1`
selpolicy=`echo $seltmdesc|cut -d: -f2`
if [[ "x$selpolicy" = "xsnapshot" ]]; then
    tmstamp=`echo $seltmdesc|cut -d: -f3`
    seltm="$seltm/$tmstamp"
fi

pd=`pwd -P`
date
echo "Stop Jaguar ..."
## do stop jaguar
cd $JAGUAR_HOME/bin
./jaguarstop
cd $pd


########################### move current data files to $DATAABAN dir ########################################
tenants=`/bin/ls -d $JAGUAR_HOME/data/*/`
echo "Backup current data to data.abandoned"
/bin/mkdir -p $JAGUAR_HOME/$DATAABAN
/bin/rm -rf $JAGUAR_HOME/$DATAABAN
/bin/mv -f  $JAGUAR_HOME/data $JAGUAR_HOME/$DATAABAN
/bin/mkdir -p $JAGUAR_HOME/data
echo


########################### move/copy data and wallog files for each tenant  ###############################
echo "Copy data and log files from backup directory ..."
for tdir in $tenants
do
    t=`basename $tdir`
    if [[ "x$t" = "xlog" ]]; then
        continue
    fi
    if [[ "x$t" = "xwallog" ]]; then
        continue
    fi

    ########## current data files have been moved to $JAGUAR_HOME/$DATAABAN 20 lines above ##
    ######### copy tenant data files from backup   ##########################################
    echo /bin/cp -rf $JAGUAR_HOME/backup/$seltm/$t  $JAGUAR_HOME/data/
    /bin/cp -rf $JAGUAR_HOME/backup/$seltm/$t  $JAGUAR_HOME/data/


    ######### move and copy  log files of tenant ##############################
    echo /bin/mkdir -p $JAGUAR_HOME/$LOGABAN/$t/cmd
    /bin/mkdir -p $JAGUAR_HOME/$LOGABAN/$t/cmd

    src="$JAGUAR_HOME/log/$t/cmd"
    dst="$JAGUAR_HOME/$LOGABAN/$t/cmd"
    echo "movefiles $src ===> $dst"
    movefiles $src $dst
    
    src="$JAGUAR_HOME/backup/$seltm/log/$t/cmd"
    dst="$JAGUAR_HOME/log/$t/cmd"
    echo "copyfiles $src ===> $dst"
    copyfiles $src $dst

done
##################################################################################################


echo
date
echo "Start Jaguar ..."
cd $JAGUAR_HOME/bin
if ./jaguarstatus; then
    ### still running
    sleep 30
fi
echo
./jaguarstart

cd $pd

