#!/bin/sh

CACHEDIR=$HOME/.cache/trimTmp

getAllOccurrences() {
    :> $CACHEDIR
    find . -print0 | while read -d $'\0' file
    do
	echo "$file" | grep " " > /dev/null

	if [ $? -eq 1 ]; then
	    continue
	fi
 
	echo "$file -> ${file// /}"

	echo "$file" >> $CACHEDIR
    done
}

getNewOccurrences() {
    getAllOccurrences > /dev/null

    for file in `cat $CACHEDIR`
    do
    	echo "$file" | grep " " > /dev/null

	if [ $? -eq 1 ]; then
	    continue
	fi
 
	echo "$file -> ${file// /}"
  	mv "$file" "${file// /}"

	getNewOccurrences

	exit
    done
}

# IFS: https://bash.cyberciti.biz/guide/$IFS
doTheTrimming() {
    #touch $CACHEDIR

    getAllOccurrences

    echo -n "Do you want all the changes? [y/N] "
    read answer

    IFS=$'\n'

    if [ $answer = "y" ]; then
	for file in `cat $CACHEDIR`
	do
	    echo "$file" | grep " " > /dev/null

	    if [ $? -eq 1 ]; then
		continue
	    fi
 
	    echo "$file -> ${file// /}"
	    mv "$file" "${file// /}"
	    
	    getNewOccurrences
	    
	    exit
	done
    fi

    #rm $CACHEDIR
}

doTheTrimming