#!/bin/ksh
#
#
# Copyright (C) Comunicacion Integral, Las Palmas de Gran Canaria, 1997
#
# Converts files from the form 
# '<name><ext>.<num>' to '<name><num>.<ext>'
# by linking them
#

# 
# Variables
#
path="."
name=""
ext=""
from=""
to=""
verbose=""

#
# Utilities
#
function usage
{
    echo "usage:\tlinkFile [-h] [-v] [-p <path>] [-n <name> -e <ext> -f <from> -t <to>]"
    echo "\t-h\t\tPrints this help"
    echo "\t-v\t\tVerbose mode"
    echo "\t-p <path>\tBase path for all the files"
    echo "\t-n <name>\tPrefix name of the files"
    echo "\t-e <ext>\tExtension of the files"
    echo "\t-f <from>\tSequence starting point"
    echo "\t-t <to>\t\tSequence ending point"
    echo "\n"
    exit 1;
}

retval=""
function getString # prefix value
{
    prefix=$1
    value=$2
    echo "$prefix [$value]: \c"
    read input < /dev/tty
    if [[ $input != "" ]]
    then
	retval=$input
    else
	retval=$value
    fi
}

function askUser
{
    getString "Enter path prefix" $path
    path=$retval
    getString "Enter name prefix" $name
    name=$retval
    getString "Enter extension" $ext
    ext=$retval
    getString "Enter sequence starting value" $from
    from=$retval
    getString "Enter sequence ending value" $to
    to=$retval
}


# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------

#
# File linking utility
#
echo "File linking utility\n"


#
# Extract arguments
#

set -- `getopt hvp:n:e:f:t: $*`

if [[ $? -ne 0 ]]
then
    usage
fi

for arg in $*
do
	case $arg in
	-h) usage; shift 1;;
	-v) verbose="y"; shift 1;;
	-p) path=$2; shift 2;;
	-n) name=$2; shift 2;;
	-e) ext=$2; shift 2;;
	-f) from=$2; shift 2;;
	-t) to=$2; shift 2;;
	esac
done


#
# Check arguments
#
asked=""

while :
do

if [[ "$name" = "" && "$ext" = "" && "$from" = "" && "$to" = "" ]]
then
    askUser
    asked="y"
fi

if [[ "$name" != "" && "$ext" != "" && "$from" != "" && "$to" != "" ]]
then
    break
else
    if [[ "$asked" != "" ]]
    then
	echo "\n"
	echo "You need to fill at least the name, extension, from and to values"
	echo "\n"
	askUser
    else
        usage
    fi
fi

if [[ $from -gt $to ]]
then
    echo "From value: $from is greater than To value: $to !"
fi

done 


#
# Loop
#
#echo "Arguments: [$name] [$ext] [$from] [$to]"

while [[ $from -le $to ]]
do
    sourceName=$path/$name$ext.$from
    targetName=$path/$name$from.$ext
    if [[ ! -r $sourceName ]]
    then
	echo "Source file does not exist: [$sourceName]"
    else
	if [[ -r $targetName ]]
	then
	    echo "Target file already exist: [$targetName]"
	else
	    if [[ $verbose != "" ]]
	    then
		echo "Linking: $sourceName ---> $targetName"
	    fi
	    /bin/ln -s $sourceName $targetName
	fi
    fi
    from=$(($from + 1))
done


#
# Done
#
exit 0

