#!/bin/bash

if [ -f /etc/fidonms ]; then
    . /etc/fidonms
fi

if [ -z "$NMSBASE" ]; then
    NMSBASE=/opt/fidonms
fi

if [ -z "$FIDOBASE" ]; then
    FIDOBASE=/var/spool/ftn
fi

INBDIR=$FIDOBASE/inbound/
TMPDIR=$FIDOBASE/.tmp/
FLGDIR=$FIDOBASE/flags/

declare -a inflist=()
readarray -t inflist < <(ls -A1 $INBDIR)

infcnt=${#inflist[@]}

# FileActions is a configfile of form <REGEXPFILTER> <ACTION> <ACTIONPATH>
# REGEXPFILTER is file filtering string in form of bash regexp ^[Pp][Oo][1..9]$
# ACTION is on of the raise delete move 
#   raise - raises flag with short name
#   delete - deletes inb file ( need any ACTIONPATH, even -)
#   move - moves inb file to location
# Actionscript is a script called when file or area is updated

declare -a fa_flt=()
declare -a fa_act=()
declare -a fa_path=()

if [ -f $NMSBASE/etc/fileactions ]; then
	while read -r line; do
		if [[ ! "$line" =~ ^# ]] && [[ -n "$line" ]]; then
			fa_flt+=( "$(echo -ne "$line" | awk '{ print $1 }')" )
			fa_act+=( "$(echo -ne "$line" | awk '{ print $2 }')" )
			fa_path+=( "$(echo -ne "$line" | awk '{ print $3 }')" )
		fi
	done < $NMSBASE/etc/fileactions
	
	for i in ${!fa_flt[@]}; do
	    echo "elem $i: filter: ${fa_flt[$i]}, action: ${fa_act[$i]}, path: ${fa_path[$i]}"
	done
fi

if [ "$infcnt" -gt "0" ]; then
    for item in "${inflist[@]}"; do
	for i in ${!fa_flt[@]}; do
	    if [[ $item =~ ${fa_flt[$i]} ]]; then
		echo "File $item equiv ${fa_flt[$i]}"
		# Check action and do it
		if [[ "${fa_act[$i]}" == "raise" ]]; then
		    echo "Raise! ${fa_path[$i]}"
		    touch "${FLGDIR}/${fa_path[$i]}"
		fi
		
		if [[ "${fa_act[$i]}" == "delete" ]]; then
		    rm -vf "${INBDIR}/${inflist[$item]}"
		fi
		
		if [[ "${fa_act[$i]}" == "move" ]]; then
		    mv -v "${INBDIR}/${inflist[$item]}" "${fa_path[$i]}"
		fi
	    else
		echo -ne "."
		
	    fi
	done
    done
fi