#!/bin/bash
# Move mp3 files older than today into subfolders based on name prefix

SOURCE_DIR="/home/tradio2022/my.mrg9999.com/daily"
TARGET_DIR="/home/tradio2022/my.mrg9999.com/daily/0Done"
LOG_FILE="$SOURCE_DIR/Moveold.txt"

# Set timezone and get current date
export TZ="Europe/London"
current_date_time=$(date)

# Log the run time
echo "Move old files executed $current_date_time" >> "$LOG_FILE"

# Make sure the target base folder exists
mkdir -p "$TARGET_DIR"

# Loop through .mp3 files older than today
find "$SOURCE_DIR" -maxdepth 1 -type f -name "*.mp3" -daystart -mtime +0 | while read -r file; do
    filename=$(basename "$file")
    
    # Extract prefix before the date (up to the last dash before the date)
    prefix=$(echo "$filename" | sed -E 's/-[0-9]{4}-[0-9]{2}-[0-9]{2}.*$//')

    # Destination subdirectory
    dest_dir="$TARGET_DIR/$prefix"

    # Create subdirectory if it doesn't exist
    mkdir -p "$dest_dir"

    # Move the file
    mv "$file" "$dest_dir/"
    
    # Log the move
    echo "Moved $filename to $dest_dir" >> "$LOG_FILE"
done
