#!/bin/bash

FWWWHOME="$HOME/fwww"

function cleanupdir_layer2
{
    parentdir=$1

    # Loop through all first-level child directories
    for child in "$parentdir"/*/; do
        [ -d "$child" ] || continue

        #echo "Checking child directory: $child"
        # Find subdirectories under this child that are older than 3 days
        find "$child" -mindepth 1 -maxdepth 1 -type d -ctime +3 | while read -r subdir; do
            echo "Deleting old subdirectory: $subdir"
            stat -c "%s bytes  [%F] %A %x %n" $subdir
            echo "/bin/rm -rf $subdir"
            /bin/rm -rf "$subdir"
        done
    done
}

function cleanupdir_layer1
{
    parentdir=$1

    find "$parentdir" -mindepth 1 -maxdepth 1 -type d -ctime +3 | while read -r subdir; do
        echo "Deleting old child directory: $subdir"
        stat -c "%s bytes  [%F] %A %x %n" $subdir
        echo "/bin/rm -rf $subdir"
        /bin/rm -rf "$subdir"
    done
}

################### main ####################################################

# Exit if directory does not exist
[ ! -d "$FWWWHOME" ] && echo "Directory not found: $FWWWHOME" && exit 1

while true
do
    date
    cleanupdir_layer1 $FWWWHOME/upstream
    cleanupdir_layer2 $FWWWHOME/downstream

    sleep 3600
done



