#!/bin/bash
source $AK_LIBDIR/_ak_ipfs
source $AK_LIBDIR/_ak_log

_ak_zchain_reset(){
    echo "Reseting ZLATEST to ZGENESIS"
    cp $ZGENESIS $ZLATEST
    if [ $? != 0 ]; then exit 1; fi

    echo "Make sure /zarchive folder exists within IPFS FS"
    _ak_ipfs_files_mkdir /zarchive
    if [ $? != 0 ]; then echo "Folder already there"; fi

    echo "Archive the previous ZLATEST"
    _ak_ipfs_files_cp /zlatest /zarchive/$(date -u +%s)-$(_ak_ipfs_files_stat /zlatest | head -n 1)
    if [ $? != 0 ]; then exit 1; fi

    echo "Removing previous /zlatest entry"
    _ak_ipfs_files_rm /zlatest
    if [ $? != 0 ]; then exit 1; fi

    echo "Copying reset ZLATEST"
    CZLATEST="$(cat $ZLATEST)"
    _ak_ipfs_files_cp /ipfs/$CZLATEST /zlatest
    if [ $? != 0 ]; then exit 1; fi

    echo "Publishing new (reset) ZLATEST"
    _ak_ipfs_name_publish --key=zchain /ipfs/$(cat $ZLATEST)
    if [ $? != 0 ]; then exit 1; fi

    ak-config --publish
    if [ $? -ne 0 ]
    then
        _ak_log_error "Could not publish new configuration"
        exit 1
    fi

    echo "Reset was successful"
    exit 0
}

_ak_zchain_rebase(){
    if [ ! -n "$1" ]; then exit 1; fi
    ZTARGET="$1"
    echo "Reseting ZLATEST to ZTARGET"
    echo $ZTARGET > $AK_ZLATEST
    if [ $? != 0 ]; then exit 1; fi

    echo "Make sure /zarchive folder exists within IPFS FS"
    _ak_ipfs_files_mkdir /zarchive
    if [ $? != 0 ]; then echo "Folder already there"; fi

    echo "Archive the previous ZLATEST"
    _ak_ipfs_files_cp /zlatest /zarchive/$(date -u +%s)-$(_ak_ipfs_files_stat /zlatest | head -n 1)
    if [ $? != 0 ]; then exit 1; fi

    echo "Removing previous /zlatest entry"
    _ak_ipfs_files_rm /zlatest
    if [ $? != 0 ]; then exit 1; fi

    echo "Copying rebased ZLATEST"
    CZLATEST="$(cat $AK_ZLATEST)"
    _ak_ipfs_files_cp /ipfs/$CZLATEST /zlatest
    if [ $? != 0 ]; then exit 1; fi

    echo "Publishing new (rebased) ZLATEST"
    _ak_ipfs_name_publish --key=zchain /ipfs/$(cat $AK_ZLATEST)
    if [ $? != 0 ]; then exit 1; fi

    ak-config --publish
    if [ $? -ne 0 ]
    then
        _ak_log_error "Could not publish new configuration"
        exit 1
    fi
    echo "Rebase was successful"
    exit 0
}

_ak_zchain_extract_cids(){
    if [ ! -z $1 ] && [ -n "$1" ]
    then
        ak zchain --crawl $1 | jq  -M | grep Qm | sed -e 's/".*"://g; s/ //g; s/[{,"]//g' | sort | uniq
    else
        ak zchain --crawl | jq -M | grep Qm | sed -e 's/".*"://g; s/ //g; s/[{,"]//g' | sort | uniq
    fi
}

_ak_zchain_extract_data_cids(){
    if [ ! -z $1 ]
    then
        ak zchain --crawl $1 | jq | grep ipfs | awk '{print $2}' | sed -e 's/"//g;s/,//g'
    else
        ak zchain --crawl | jq | grep ipfs | awk '{print $2}' | sed -e 's/"//g;s/,//g'
    fi
}

_ak_zchain_calculate_size(){
    temp="$(_ak_make_temp_directory)"
    cd $temp
    if [ ! -z $1 ] && [ -n "$1" ]
    then
        _ak_zchain_extract_cids $1 > to_stats
    else
        _ak_zchain_extract_cids > to_stats
    fi
    sum=0 ; while IFS="" read -r p || [ -n "$p" ]
    do
        if [ "$p" != "" ]
        then
            _ak_ipfs_get $p
            num="$(du -bs --apparent-size $p | cut -d $'\t' -f 1)"
        else
            num=0
        fi
        sum=$(expr $sum + $num )
    done < to_stats
    echo "Chain is : $sum bytes"
    cd ~
    rm -rf $temp
}

_ak_zchain_crawl(){
    entrance="$(cat $AK_ZLATEST)"
    verify=1
    limit=0
    fromIpns=0
    while [ "$#" ]; do
        case "$1" in
            -h | --help)
                printf "Zchain crawler
==============

ak zchain --crawl [-N | --no-verify] [-l | --limit <number>] [zblock]

ak zchain --crawl [-N | --no-verify] [-l | --limit <number>] -n <zchain>

Usage:

    --help, -h                             Print this help and exit

    --chain <ipns-link>, -n <ipns-link>    Crawl specified chain

    --no-verify, -N                        Don't verify signatures

    <ipfs-link>                            Specify IPFS CID for entrance

Note that combined flags don't work for now
Running with no flags crawls your chain based on AK_ZLATEST environment
variable
"
                exit 1
                ;;
            -l | --limit)
                limit=$2
                shift 2
                ;;
            -N | --no-verify)
                verify=0
                shift
                ;;
            -n | --chain | --ipns)
                fromIpns=1
                ipns=$1
                shift
                ol=$1
                entrance="$(_ak_ipns_resolve $1)"
                if [ $? -ne 0 ]
                then
                    _ak_log_error "Could not resolve IPNS name"
                    exit 1
                fi
                shift
                ;;
            *)
                test="$1"
                if [ ! -z "$test" ] && [ $fromIpns -eq 0 ]
                then
                    _ak_ipfs_cid_v0_check "$test"
                    entrance="$test"
                elif [ -z "$entrance" ] && [ $fromIpns -eq 1 ]
                then
                    entrance="$(cat $AK_ZLATEST)"
                fi
                break
        esac
    done
    # We assign the IPFS CIDv0 of an empty file as this is used
    # as our GENESIS block, hence the "seed" that the tree grows
    # from.
    seed="$(cat $AK_ZGENESIS)"
    # We assume that we found the entrance inside a block, hence
    # ZBLOCK is labeled as previous
    zblock="$entrance"
    # Enter temp folder
    TEMPASSIN="$(_ak_make_temp_directory)"
    cd $TEMPASSIN
    counter=0
    # The loop
    # We break the loop from inside the loop
    while true
    do
        if [ $counter -eq 0 ]
        then
            echo -n '['
        fi
        counter=$(($counter + 1))
        _ak_zblock_show "$zblock"
        if [ $limit -ne 0 ] && [ $limit -eq $counter ]
        then
            echo -n ']'
            exit 0
        else
            echo -n ','
        fi
    done
}

_ak_zchain_crawl_self(){
    _ak_zchain_crawl
}

_ak_zchain_crawl_remote_ipfs(){
    _ak_zchain_crawl $1
    #ak enter $1
}

_ak_zchain_crawl_remote_ipns(){
    _ak_zchain_crawl -n $1
    #ak enter -n $1
}