#!/bin/bash
# This script continuously monitors a source directory and moves any files matching the specified extension
# to a destination directory. It checks for new files every interval (default 10 seconds).
# Usage: ./script.sh --source-dir|-s <source_dir> --dest-dir|-d <dest_dir> --extension|-e <extension> [--interval|-i <seconds>]
# Or set MV_SOURCE_DIR, MV_DEST_DIR, MV_EXTENSION and MV_INTERVAL environment variables before running
# Example: ./script.sh -s /home/user/downloads -d /home/user/documents -e "*.pdf" -i 30

while [[ $# -gt 0 ]]; do
    case "$1" in
        --source-dir|-s) MV_SOURCE_DIR="$2"; shift 2 ;;
        --dest-dir|-d) MV_DEST_DIR="$2"; shift 2 ;;
        --extension|-e) MV_EXTENSION="$2"; shift 2 ;;
        --interval|-i) MV_INTERVAL="$2"; shift 2 ;;
        *) echo "Unknown parameter: $1"; exit 1 ;;
    esac
done

MV_SOURCE_DIR=${MV_SOURCE_DIR:-$MV_SOURCE_DIR}
MV_DEST_DIR=${MV_DEST_DIR:-$MV_DEST_DIR}
MV_EXTENSION=${MV_EXTENSION:-$MV_EXTENSION}
MV_INTERVAL=${MV_INTERVAL:-10}

if [ -z "$MV_SOURCE_DIR" ] || [ -z "$MV_DEST_DIR" ] || [ -z "$MV_EXTENSION" ]; then
    echo "Error: MV_SOURCE_DIR, MV_DEST_DIR and MV_EXTENSION must be provided via environment variables or arguments"
    echo "Usage: $0 --source-dir|-s <source_dir> --dest-dir|-d <dest_dir> --extension|-e <extension> [--interval|-i <seconds>]"
    echo "Or set MV_SOURCE_DIR, MV_DEST_DIR, MV_EXTENSION and MV_INTERVAL environment variables"
    echo "Example: $0 --source-dir /home/user/downloads --dest-dir /home/user/documents --extension *.pdf --interval 30"
    echo "Or: export MV_SOURCE_DIR=/home/user/downloads MV_DEST_DIR=/home/user/documents MV_EXTENSION=*.pdf MV_INTERVAL=30"
    exit 1
fi

if [ ! -d "$MV_DEST_DIR" ]; then
    echo "Error: Destination directory $MV_DEST_DIR does not exist"
    exit 1
fi

shopt -s nullglob  # This prevents errors when no matches are found
while true; do
    for file in "$MV_SOURCE_DIR"/$MV_EXTENSION; do
        if [ -f "$file" ]; then
            echo "Moving: $file"
            mv "$file" "$MV_DEST_DIR"
        fi
    done
    sleep $MV_INTERVAL
done
