#!/bin/sh

# Uncomment this line to see the entire code path for debugging
#set -x

# script
script=$0

# uid and user
uid=`id | cut -f2 -d'=' | cut -f1 -d'('`
user=`id | cut -f2 -d'(' | cut -f1 -d')'`

# scriptdir and scriptdirparent
scriptdir=`dirname $script`
is_abs=`echo $scriptdir | grep '^\/'`
if [ "x$is_abs" = "x" ]; then
    scriptdir=`pwd`/$scriptdir
fi

scriptdir=`echo $scriptdir | sed -e 's/\/\.$//'`
scriptdirparent=`echo $scriptdir | sed -e 's/\/[^\/]*$//'`



# pass the expected number of args as the first param
#  and the actual number of args as the second param
#
# Ex: check_nargs 1 $#
#
check_nargs() {
    if [ "x$1" != "x$2" ]; then
        echo
        echo "$0 expects $1 arg(s), not $2"
        echo
        exit 1
    fi
}



make_symlink() {
    src=$1
    dst=$2

    if [ "x$src" = "x" ]; then
        echo 1
    else
        if [ "x$dst" = "x" ]; then
            echo 1
        else
            if [ -h $dst ]; then
                rm $dst;
            fi

            ln -fs $src $dst

            echo $?
        fi
    fi
}


# prompt_input()
#
# $1 - prompt string
# $2 - sed regular expression of 'valid' input string
# $3 - String to echo if entry is invalid
# $4 - optional name of function to further validate input string
#      This function will be passed the string that was typed
#      and must print '1' on successful validation
#                     '0' otherwise
#
prompt_input() {
    while [ 1 ]; do
        printf "$1"
        read ans
        #echo "pattern: $2"
        match=`echo $ans | sed -n $2`
        #echo "match: $match"
        if [ "x$match" != "x" ]; then
            if [ "x$4" = "x" ]; then
                break;
            else
                # looks like we're going to validate the string 
                # remember, a return value of '1' means we've got a good string
                res=`$4 $ans`
                if [ "x$res" = "x1" ]; then break; fi
            fi
        fi

        if [ "x$3" != "x" ]; then echo "$3"; fi
 
    done
}

# is_dir()
#
# returns 1 if argument is directory
#         0 otherwise
#
is_dir() {
    if [ "x$1" = "x" ]; then
        echo "0"
    else
        if [ -d $1 ]; then
            echo "1" 
        else 
            echo "0"
        fi
    fi 
}

#
# Some sample prompts that can be used
#
#prompt_input "This is the text [yes/no]" "/^[YyNn]$\|[Yy][Ee][Ss]\|[Nn][Oo]/p"
#prompt_input "Any string with at least one char: " "/^..*$/p" "** Need a string with at least one char **"
#prompt_input "Enter a valid dir: " "/^..*$/p" " ** Not a valid dir **" "is_dir"

