#!/bin/bash
die () {
    echo >&2 "$@"
    exit 1
}

[ "$#" -eq 8 ] || die "Usage: $0 num_slots num_bays num_pools num_servers first_free_slot disks_per_pool volumes_per_pool volumes_per_server"

TOTAL_SLOTS=$1
TOTAL_BAYS=$2
TOTAL_POOLS=$3
TOTAL_SERVERS=$4
START_SLOT=$5
DISKS_PER_POOL=$6
VOLUMES_PER_POOL=$7
VOLUMES_PER_SERVER=$8
POOL_PREFIX="pool"
VOL_PREFIX="volume"

ssh -i /home/rcb/rcb_rsa admin@seamicro "enable; config; storage assign-clear all"
#loop over this for all values of pool num. do external and internal
for (( SLOT=$START_SLOT; SLOT<$TOTAL_SLOTS; SLOT++ ))
do
	echo "SLOT #$SLOT"
	for (( POOL_NUM=0; POOL_NUM<$TOTAL_POOLS; POOL_NUM++ ))
	do
		echo "REMOVING VOLs FROM POOL #$POOL_NUM"
		ssh -i /home/rcb/rcb_rsa admin@seamicro "enable; storage delete volume-prefix $SLOT/$POOL_PREFIX-$POOL_NUM/$VOL_PREFIX count $VOLUMES_PER_POOL"
	done
	echo "REMOVING POOLS FROM SLOT #$SLOT"
	ssh -i /home/rcb/rcb_rsa admin@seamicro "enable; storage delete pool $SLOT/all"
done

declare -a POOL_DISK_ARRAY
disks_in_current_pool=0
current_pool=0
disk_list_string=""
for (( SLOT=$START_SLOT; SLOT<$TOTAL_SLOTS; SLOT++ ))
do
        for (( BAY=0; BAY<$TOTAL_BAYS; BAY++ ))
        do
                disk_list_string="$disk_list_string$SLOT/$BAY,"
                ((disks_in_current_pool++))
                if [ $disks_in_current_pool -ge $DISKS_PER_POOL  ] ; then
                        POOL_DISK_ARRAY[$current_pool]=${disk_list_string%?}
                        disk_list_string=""
                        ((current_pool++))
                        disks_in_current_pool=0
                fi
        done
done

vols_in_current_server=0
current_server=0
for (( SLOT=$START_SLOT; SLOT<$TOTAL_SLOTS; SLOT++ ))
do
        echo "SLOT #$SLOT"
        for (( POOL_NUM=0; POOL_NUM<$TOTAL_POOLS; POOL_NUM++ ))
        do
                echo "CREATING POOL #$POOL_NUM"
                ssh -i /home/rcb/rcb_rsa admin@seamicro "enable; storage create pool $SLOT/$POOL_PREFIX-$POOL_NUM disk ${POOL_DISK_ARRAY[$POOL_NUM]}"
		echo "CREATING VOLUMES"
                ssh -i /home/rcb/rcb_rsa admin@seamicro "enable; storage create volume-prefix $SLOT/$POOL_PREFIX-$POOL_NUM/$VOL_PREFIX size $VOL_SIZE count $VOLUMES_PER_POOL"
		for (( VOL_NUM=0; VOL_NUM<$VOLUMES_PER_POOL; VOL_NUM++ )) 
		do
		        echo "ASSIGN VOLUME X TO SERVER Y"
        		ssh -i /home/rcb/rcb_rsa admin@seamicro "enable; configure; storage assign $current_server/0 $vols_in_current_server volume $SLOT/$POOL_PREFIX-$POOL_NUM/$VOL_PREFIX-$VOL_NUM"
			((vols_in_current_server++))
        	        if [ $vols_in_current_server -ge $VOLUMES_PER_SERVER  ] ; then
                	        ((current_server++))
                        	vols_in_current_server=0
	                fi
		done
        done
done


