#!/bin/bash

# Date: 26.03.2023
# 
# Summary:
# Search and find .D64 files and create a swap file for the Pi1541
#
# Remarks:
# - checked with bash and zsh under MacOS 11.6.8
#    
# Change log:
# ---

# set the directory to search in (./ == actual directory)
directory=./

# loop through all subdirectories
for subdir in "$directory"/*/; do
    # count the number of d64 files in the subdirectory
    count=$(find "$subdir" -maxdepth 1 -type f -name "*.d64" | wc -l)                                   # increase -maxdepth if more subfolders should be searched

    # if there are 2 or more d64 files, create a text file with the file names
    if [ "$count" -ge 2 ]; then
            
        # create the text file
        lst_file="$subdir$(basename "$subdir").LST"
        touch "$lst_file"

        # find, 
        d64_files=$(find "$subdir" -maxdepth 1 -type f -name "*.d64" -exec basename {} \;)   # increase -maxdepth if more subfolders should be searched

        # sort and 
        sorted_files=( $(
            for file in "${d64_files[@]}"; do
                echo "$file"
            done | sort
        ) )

        # add new line behind each name and write the d64 files to the text file
        echo "${sorted_files[@]}" | tr ' ' '\n' > "$lst_file"
        
    fi
done

# create a log file with the names of the newly created text files
find "$directory" -maxdepth 2 -type f -name "*.LST" -exec basename {} \; > "$directory/LST_files.txt"   # maxdepth should be +1 than above
