#!/bin/bash

target=${1}

# Define the source and target directories
source_dir="/var/www/learnup/$target/upcoming"
target_dir="/var/www/learnup/$target"

# Find the oldest file in the source directory
oldest_file=$(find "$source_dir" -type f -printf "%T+ %p\n" | sort | head -n 1 | cut -d' ' -f2-)

echo "Oldest file: $oldest_file found."

# Check if the oldest file exists and then move it to the target directory
if [ -f "$oldest_file" ]; then
    oldest_file_name=$(basename "$oldest_file" | sed 's/\.[^.]*$//')
    echo "$oldest_file_name" > "$target_dir/index.txt"
    read -r FIRST_LINE < "$oldest_file"
    echo "$FIRST_LINE" >> "$target_dir/index.txt"
    mv "$oldest_file" "$target_dir"
    echo "Moved the oldest file: $oldest_file to $target_dir"
else
    echo "No files found in $source_dir to move."
fi
