#! /bin/bash
#
# AMS2Rpi - Converts MS Arduino IDE Sketch names to RPI Arduino IDE Sketch names
#
# SDsolar 2017-01-29
#
# Reason: Arduino IDE on MS inserts underscore characters in file & directory names
# Arduino IDE on Rpi rejects all but alphanumeric characters
#
# Solution: Remove all but alphanumeric characters
# and capitalize each word in the names
#
# Usage:
# Install Raspbian Arduino IDE 2:1.0.5 on the Raspberry Pi 3
# Use a USB flash drive to copy sketches and libraries from the MS-based Arduino IDE
# On the Rpi, copy the libraries directory to ~/sketchbook/libraries
# On the Rpi, copy the sketches directory to ~sketchbook/AMSsketches
# Copy this script to your home directory as AMS2Rpi using Chromium
# cd
# chmod +x AMS2Rpi
# ./AMS2Rpi (This will take some time)
# cat /tmp/AMS2Rpi | grep "AMSsketches" >~/AMSRpiQ
# chmod +x ~/AMS2RpiQ
# ~/AMS2RpiQ
# Open the Rpi Arduino IDE
#
# Alternatively, if you have a lot of sketches you might want to
# change the "mv -i" below to "mv"
# and cat it into AM2SRpiX above
# so you don't need to answer "y" for every rename.
#
# Props to Marco Fioretti for his article at http://www.techrepublic.com/blog/linux-and-open-source/how-to-remove-weird-characters-from-file-and-directory-names-automatically/
# ---------------------------------------------------------------------
rm -f /tmp/AMS2R*
cd $1
find . | awk '{ print length(), $0 | "sort -n -r" }' | \
grep -v '^1 \.$' | cut -d/ -f2- > /tmp/AMS2Rpi_1
touch /tmp/AMS2Rpi_2
while read line
do
BASE=`basename "$line"`
NEWBASE=`basename "$line" | perl -e '$N = <>; chomp ($N); $N =~ s/[^a-zA-Z0-9.]//g; $N =~ s/_+/_/g; $N= lc($N); $N =~ s/_([a-z])/_.uc($1)/eg; print ucfirst($N);' `
if [ "$BASE" != "$NEWBASE" ]
then
OLDPATH=$(echo "$line" | sed -r 's/([^a-zA-Z0-9./_-])/\\\1/g')
DIR=$(dirname "$line" | sed -r 's/([^a-zA-Z0-9./_-])/\\\1/g')
echo "mv -i $OLDPATH $DIR/$NEWBASE" >> /tmp/AMS2Rpi_2
fi
done </tmp/AMS2Rpi_1
rm -f /tmp/AMS2Rpi_1
mv /tmp/AMS2Rpi_2 /tmp/AMS2RPiAMS2Rpi
exit