#!/bin/bash

#set -x

function usage {
    echo "Usage: $0 [options]"
    echo " -h --help : display this help and exit"
    echo " -s --start : start duniter at the end of the synchronization"
    echo " -n --node node_adress : node used to start synchronization (default g1.duniter.org)"
    echo " -m --mdb mdb "
    echo " -a --all-data : include peers and mempool"
}

node="g1.duniter.org"
mdb=""
start=""
mdb="duniter_default"
include_all_data=""
# parameter analysis
while getopts "ahsn:m:-:" option; do
    case "${option}" in
        -)
           case "${OPTARG}" in
                help)
                    usage
                    exit 0
                    ;;           
                start)
                    start="true"
                    ;;
                node)
                    node="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 ))
                    ;;  
                mdb)
                    mdb="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 ))
                    ;;     
                all-data)
                    include_all_data="true"
                    ;;
                *)
                    if [ "$OPTERR" = 1 ] && [ "${optspec:0:1}" != ":" ]; then
                        echo "Unknown option --${OPTARG}" >&2
                        usage
                        exit 1;
                    fi
                    ;;
            esac;;
        s)
            start="true"
            ;;
        a)
            include_all_data="true"
            ;;    
        n)
            node=${OPTARG}
            ;;
        m)
            mdb=${OPTARG}
            ;;
        h)
            usage
            exit 0
            ;;
        *)
            usage 
            exit 1;
            ;;
    esac
done

function clean_tmpfs {
  rm -rf /dev/sbm/duniter
}

# pre-synchronization
duniter stop --mdb ${mdb}
clean_tmpfs

# synchronization
duniter --home /dev/shm/duniter sync ${node} --mdb ${mdb}

# reset data
duniter reset data --mdb ${mdb}

# copy data
cp -rf /dev/shm/duniter/${mdb}/data ~/.config/duniter/${mdb}/data

if [ -n "${include_all_data}" ]; then
  cp -f /dev/shm/duniter/${mdb}/peers.db ~/.config/duniter/${mdb}/peers.db
  cp -f /dev/shm/duniter/${mdb}/duniter.db ~/.config/duniter/${mdb}/duniter.db
  cp -f /dev/shm/duniter/${mdb}/txs.db ~/.config/duniter/${mdb}/txs.db
fi

# post-synchronization
clean_tmpfs

if [ -n "${start}" ]; then
   duniter start --mdb ${mdb}
fi



