#! /bin/bash

usage() {
    echo 'Usage: bigfile-repartition file Nfile block ...' >&2
    exit;
}

fail () {
    exit;
}


VERBOSE=0
while getopts ":v" opt; do
    case $opt in 
        v )
        VERBOSE="-v"
        ;;
        \? )
        usage
        ;;
    esac
done

shift $(($OPTIND-1))
ROOT=`dirname $0`
FILE=$1
shift
NFILE=$1
shift

repart() {
    local BLOCK
    BLOCK=$1
    

    if [ $VERBOSE ]; then
        echo Repartitioning $BLOCK >&2
    fi;
    $ROOT/bigfile-rename $FILE $BLOCK ${BLOCK}-REPBAK || fail
    $ROOT/bigfile-copy $VERBOSE -n $NFILE $FILE ${BLOCK}-REPBAK ${BLOCK} ||fail
    $ROOT/bigfile-rm $FILE ${BLOCK}-REPBAK ||fail
}
if [ -z $1 ]; then
    BLOCKS=`$ROOT/bigfile-ls $FILE`
else
    BLOCKS="$*"
fi

for block in $BLOCKS ; do
    ( repart $block ) &
done
wait
