#!/bin/bash
#
# Monitors a folder for new files and creates symbolic links with
# incrementing indexes.
#
# Dependencies: inotify-tools
#
# Usage: t2dmon [OPTION...] [FOLDER]

# Default option
FOLDER="."         # folder to monitor
LNAME="wurst.pcap" # name to use for the symbolic links
INDEX=0            # start index for the symbolic links

# Name of the script
SNAME="$(basename "$0")"

printerr() {
    printf "\e[0;31mError: %s\e[0m\n" "$1" >&2
}

abort_with_help() {
    echo "Try '$SNAME --help' for more information."
    exit 1
}

# $1: name of the option
# $2: argument to validate
validate_args() {
    if [ -n "$2" ] && [ "${2:0:1}" != "-" ]; then
        return 0
    else
        printerr "Option '$1' requires an argument"
        abort_with_help
    fi
}

# $1: name of the option
# $2: argument to validate
validate_num() {
    if [ -z "$(tr -d '[0-9]' <<< "$2")" ]; then
        return 0
    else
        printerr "Invalid argument for option '$1': expected number > 0; found '$2'"
        abort_with_help
    fi
}

while [ $# -ne 0 ]; do
    case "$1" in
        -i)
            validate_args "$1" "$2"
            validate_num "$1" "$2"
            INDEX=$2
            shift
            ;;
        -o)
            validate_args "$1" "$2"
            LNAME="$2"
            shift
            ;;
        -m)
            validate_args "$1" "$2"
            validate_num "$1" "$2"
            LMAX=$2
            shift
            ;;
        -v) VERBOSE=1;;
        -h|-\?|--help)
            echo "Usage:"
            echo "    $SNAME [OPTION...] [FOLDER]"
            echo
            echo "Optional arguments:"
            echo "    FOLDER        Folder to monitor [default: $FOLDER]"
            echo
            echo "    -i index      Start indexing symbolic links with 'index' [default: $INDEX]"
            echo "    -o name       Name to use for symbolic links [default: $LNAME]"
            echo "    -m max        Maximum numbers of symbolic links to store [default: infinity]"
            echo
            echo "    -v            Enable verbose output"
            echo
            echo "    -h, --help    Show this help, then exit"
            exit 0
           ;;
        *)
            if [ -d "$1" ]; then
                FOLDER="$1"
            else
                printerr "Unknown option '$1'"
                abort_with_help
            fi
    esac
    shift
done

# Check for dependencies
if ! hash inotifywait 2> /dev/null; then
    printerr "Command inotifywait not found."
    echo "Install package 'inotify-tools'"
    exit 1
fi

# Make sure there is a trailing slash
FOLDER="$(awk '{ if (/\/$/) print; else printf "%s/\n", $0 }' <<< "$FOLDER")"

if [ $VERBOSE ]; then
    echo "Monitoring folder '$FOLDER'"
    echo "First symlink will be '$FOLDER$LNAME$INDEX'"
fi

inotifywait -m -q -e moved_to -e create --format '%f' "$FOLDER" |
    while read file; do
        newfile="$FOLDER$file"
        if [ -f "$newfile" ] && [ ! -L "$newfile" ]; then
            link="$FOLDER$LNAME$INDEX"
            if [ $VERBOSE ]; then
                echo "New file: '$newfile'"
                echo "New symlink: '$link'"
            fi
            ln -f -s "$file" "$link"
            if [ $LMAX ]; then
                nlinks=$(find "$FOLDER" -maxdepth 1 -type l | wc -l)
                if [ $nlinks -gt $LMAX ]; then
                    oldest="$FOLDER$LNAME$((INDEX-LMAX))"
                    [ $VERBOSE ] && echo "Too many links. Removing '$oldest'"
                    rm -f "$oldest"
                fi
            fi
            INDEX=$((INDEX+1))
        fi
    done
