#!/bin/bash

declare host=""
declare port=""
declare user=""
declare passwd=""
declare database=""
declare output_dir=query_output`date +%Y%m%d_%H%M%S`

function valid_ip()
{
    regex="\b(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[1-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[1-9])\b"
    ckStep2=`echo $1 | egrep $regex | wc -l`
    if [ $ckStep2 -eq 0 ]
    then
        return 0
    else
        return 1
    fi

}

read -p "Please input DWS host IP:" host
if valid_ip $host; then
    echo "invalid IP address [$host]"
    exit 1
fi

read -p "Please input DWS port:" port
read -p "Please input DWS database:" database
read -p "Please input DWS user:" user

echo -e "Please input DWS user passwd: \c"
while : ;do
    char=`
        stty cbreak -echo
        dd if=/dev/tty bs=1 count=1 2>/dev/null
        stty -cbreak echo
       `
        if [ "$char" = "" ];then
            echo
            break
        fi
        passwd="$passwd$char"
        echo -n "*"
done

echo "==========================================="
echo "host                    : ["$host"]"
echo "port                    : ["$port"]"
echo "database                : ["$database"]"
echo "user                    : ["$user"]"
echo "query output directory  : ["$output_dir"]"
echo "==========================================="

rm -rf $output_dir
mkdir $output_dir

for i in {1..99}
do
    if [ $i -lt 10 ]
    then
        query_file=Q0$i.sql
    else
        query_file=Q$i.sql
    fi

    echo ">>>>>>$query_file" |tee -a $output_dir/query_result.log
    gsql -h$host -p$port -U$user -W$passwd -d $database -o $output_dir/$query_file.out -f $query_file 2>&1 |tee -a $output_dir/query_result.log

done