#!/usr/bin/env zsh

# Input argument: path to the directory with .tar files
dir=$1

# Replace ":" with "-" in the file names
cd $dir
for file in *.tar; do
  newfile=$(echo $file | tr ':' '-')
  mv "$file" "$newfile"
done

# Loop over the unique IDs and extract files to subdirectories
for id in $(find . -name "*.tar" -type f -exec basename {} \; | grep -oP 'bitbots_\K\d+' | sort -u); do
  subdir="ID_$id"
  mkdir -p "$subdir"
  for file in *_bitbots_${id}_*.tar; do
    tar -xf "$file" -C "$subdir" --wildcards --no-anchored '*'  # Extract all files; this keeps the archive's file tree
    find "$subdir" -type f -exec mv {} "$subdir" \;  # Flatten the file tree
    rm -rf "$subdir"/home  # Remove the empty home directory left over from the extraction
    rm "$file"  # Remove the tar file after extraction
  done
done

