#! /bin/bash
MYNAME=$(basename $0)
MYDIR=$(dirname $0)
MYDIR=$(readlink -m "$MYDIR")
MYHOSTNAME=$(hostname)
VERSION="0.0.17"
VERBOSE=""
LOGFILE=""

STAT_N_FILES_PROCESSED=0

source $MYDIR/utilityfunctions.sh

#
# Prints the help text and exits.
#
function printHelpAndExit()
{
cat <<EOF
Usage:
  $MYNAME [OPTION]...

  $MYNAME - Controls test server and uploads server status file. 

  -h, --help         Print this help and exit.
  -v, --version      Print version information and exit.
  --verbose          Print more messages.
  --log-file=FILE    Store all the messages in the given file too.

  --tf               Use tensorflow to create categories.

EOF
    exit 0
}

ARGS=$(\
    getopt \
        -o hv \
        -l "help,version,verbose,log-file:,\
tf" \
        -- "$@")

if [ $? -ne 0 ]; then
    exit 6
fi

eval set -- "$ARGS"
while true; do
    case "$1" in
        -h|--help)
            shift
            printHelpAndExit
            ;;

        --verbose)
            shift
            VERBOSE="true"
            ;;

        -v|--version)
            shift
            printVersionAndExit
            ;;

        --log-file)
            shift
            LOGFILE=$(readlink -m "$1")
            shift
            ;;
        
        --tf)
            shift
            OPTION_TF="true"
            ;;

        --)
            shift
            break
            ;;

        *)
            ;;
    esac
done

function process_tf_file()
{
    local tf_dir="$1"
    local tf_graph="$2"
    local input_file="$3"
    local input_dir="$(dirname "$input_file")"
    local result
    local tmpfile=$(mktemp)

    pushd $tf_dir >/dev/null 2>/dev/null
    cat <<eof
    python -m "scripts.label_image" --graph "$tf_graph" --input_layer=Mul --image "$input_file"
eof
    # input_layer, input_height, input_width
    # https://stackoverflow.com/questions/46325799/tensorflow-for-poets-the-name-import-input-refers-to-an-operation-not-in-the
    result=$(python \
        -m "scripts.label_image" \
        --graph "tf_files/retrained_graph.pb" \
        --input_layer=Mul \
        --input_height=299 \
        --input_width=299 \
        --image "$input_file" 2>$tmpfile \
        | grep -v "^$" | grep -v "Evaluation time.*" \
        | head -n 1)
            
    name="$(echo "$result" | sed -e 's/ (/(/g' | awk -F\( '{print $1}' | tr ' ' '_')"
    value="$(echo "$result" | awk -F\( '{print $2}' | awk -F= '{print $2}')"
    value="$(echo "$value" | tr -d ')')"

    echo " input_file: $input_file"
    echo "     result: '$result'"
    echo "       name: '$name'"
    echo "      value: '$value'"
    echo "  processed: $STAT_N_FILES_PROCESSED file(s)"

    if (( $(echo "$value < 0.65" | bc -l) )); then
        name="unrecognized"
    fi
    
    echo "       name: '$name'"

    if [ -z "$name" ]; then
        printError "Failed."
        cat $tmpfile
        rm $tmpfile
        return 1
    else
        rm $tmpfile
    fi

    if [ -n "$name" ]; then
        name="$input_dir/$name"

        if [ ! -d "$name" ]; then
            mkdir "$name"
            chown pipas.pipas "$name"
            if [ ! -d "$name" ]; then
                printError "Could not create '$name'."
            fi
        fi

        mv "$input_file" "$name"
    fi

    popd >/dev/null 2>/dev/null

    let STAT_N_FILES_PROCESSED+=1
}

function process_tf()
{
    local tf_dir="$HOME/tensorflow-for-poets-2"
    local tf_graph="server_graph.pb"

    if [ ! -d "$tf_dir" ]; then
        printError "The '$tf_dir' does not exist."
        return 1
    fi

    if [ ! -f "$tf_dir/$tf_graph" ]; then
        printError "The file '$tf_dir/$tf_graph' does not exist."
        return 1
    fi

    for file in *.jpg; do
        if [ ! -f "$file" ]; then
            continue
        fi

        process_tf_file "$tf_dir" "$tf_graph" "$PWD/$file"
        #break
    done
}


if [ "$OPTION_TF" ]; then
    process_tf 
    exit $?
fi


pattern="$1"
if [ -z "$pattern" ]; then
    printError "The first argument should be the file name pattern."
fi

prefix="$2"
if [ -z "$prefix" ]; then
    prefix="file"
fi

OIFS="$IFS"
IFS=$'\n'
for file in $(find ./ -type f -name "$pattern"); do
    if [ ! -f "$file" ]; then
        printError "The '$file' is not a regular file."
        error="true"
    fi
done
IFS="$OIFS"

if [ "$error" ]; then
    exit 5
fi

n=0

OIFS="$IFS"
IFS=$'\n'
for file in $(find ./ -type f -name "$pattern"); do
    extension="${file##*.}"
    newfilename=$(printf "%s_%03d.%s" "$prefix" "$n" "$extension")

    mv "$file" "$newfilename"
    if [ $? -ne 0 ]; then
        break
    fi

    let n+=1
done
IFS="$OIFS"
