#!/bin/bash

labdir=$1
newprefix=$2

if [[ -z $labdir ]]
then
    echo "[ERROR] expect a lab directory"
    echo "will rename all labxxx.* within this directory to directory name labdirxxx.*"
    exit 1
fi

if [[ -z $newprefix ]]
then
    newprefix=$labdir
fi

{
    echo "[INFO] changing lab prefix to $newprefix"

    declare -i index=1

    pushd $labdir
    for f in $(find . -regextype egrep -regex "./lab[0-9]+x[0-9]+\..*")
    do
	if [[ $f =~ ./lab([0-9]+)x([0-9]+)\.(.+) ]]
	then	
	    width=${BASH_REMATCH[1]}
	    height=${BASH_REMATCH[2]}
	    extension=${BASH_REMATCH[3]}
	    newname="${newprefix}_${index}_${width}x${height}.$extension"
	    if [[ ! -e ./$newname ]]
	    then
		mv $f ./$newname
	    else
		echo "[ERROR] skip $f -> ./$newname since new name already used" >&2
	    fi
	fi
	index=index+1
    done	 
    popd
}
