Showing posts with label scripting. Show all posts
Showing posts with label scripting. Show all posts

Tuesday, July 05, 2011

Sync, then add new MP3s from a folder to iTunes

The "Sitch":
Like many "advanced" users, I reluctantly use iTunes because it's the most straightforward way to load my iPod. However, less than 0.01%* of my content was purchased from the iTunes store, and there is absolutely no way that I will ever allow iTunes to organize obliterate my folder and file structure. When I rip a disc, buy a $5 album from Amazon MP3, download free tracks, etc., the files get stored on a NAS, where the collection is archived.

For a while, I've been rsynching the master collection on the NAS to a local folder on the living room PC, because iTunes has exhibited poor behavior with both remote libraries (supported by my NAS) and libraries on network shares -- particularly if said share is accessed from multiple computers. (I won't go into the details, but the past issues in both of these options made a local copy highly desirable... Maybe Apple fixed all the issues I ever encountered. Maybe not. I simply don't feel like finding out.)

The Hitch:
Unlike practically every other media player in the universe, iTunes isn't programmed to fulfill the simple task of identifying that files have been added to a given folder and then importing said files into its precious little library. This meant opening iTunes and running Add to Library from its menu. There were two options: remember what you just rsynched and pick the appropriate sub-folder(s) or re-add the whole top-level folder and trust that duplicates won't be added (which generally worked.) Either way, it was manual and therefore bogus...

The Fix (for this Son of a *itch):
Enter Automator. As you can see in the top part of the (rather wide) screen snippets below, it takes a massive two steps to A.) find brand-spanking new music files in a specified folder structure and then B.) add said files to the iTunes Library. Why this has to be done with an extravagant macro-type concoction is beyond me, but the fact that is literally this trivial to accomplish was refreshing, as I haven't really messed with Automator nearly enough...

Music being synchronized to a local folder, then being added to iTunes automagically. Dogs and cats, living together! The apocalypse is nigh!!! 
After adding those two tasks to a "Workflow" in Automator, I saved it as an Application so that I could just run the bugger without opening Automator every time. The other benefit of saving as an app is that I could just add another line at the end of my rsync script and make it run by itself. That's what that little open command at the end of the script snippet above does. Note that the rsync line excludes the meta-files that are created by various OSes when the master copy on the NAS is accessed directly, and that it doesn't perform any deletions.

_____________
*: This isn't hyperbole! I have over 10k files, and exactly one track in the archived collection was purchased from the iTunes store.

Tuesday, August 25, 2009

Broadband2Go and Ubuntu 8.04 -- 1st success

No luck with NetworkManager (Bugs: Ubuntu, Gnome Network Manager).

Anyhow, the important parts:
  1. edited /etc/udev/rules.d/70-persistent-cd.rules and added ,RUN+="/usr/bin/eject %k" to the Novatel-generated entries
  2. re-inserted the card and ran lsusb to verify that the Virgin Mobile card showed up in modem mode (1410:6002)
  3. ran sudo modprobe usbserial vendor=0x1410 product=0x6002 to establish the ttyUSBx devices (I had gotten this far previously)
  4. verified that said ttys were there via ls /dev/ttyU*
  5. followed Sprint's instructions for wvdial, including sudo wvdialconf, sudo vi /etc/wvdial.conf (to set the parameters), and then sudo wvdial to establish the connection (when I tried wvdial w/o root, it couldn't modify /etc/ppp/chap-secrets or /etc/ppp/pap-secrets. I'll have to look into that, b/c root may not be strictly necessary here... I seem to recall a "dialout" group...)
  6. NOTE: the wvdialconf and /etc/wvdial.conf items above are one-time steps...
  7. NOTE: It's trivial to script the lsusb, modprobe, checking for tty, and launching wvdial tasks, and should be easy to add a launcher icon also. (UPDATE: it was pretty trivial -- see below)
  8. Killed my WiFi (via Airplane Mode), then wrote this post via the 3G goodness. Verified no ip on eth1 (my wifi), and active ip on ppp0 via ifconfig
  9. NOTE: leave the terminal window open, and simply hit <Ctrl>+C to disconnect when you're ready.
It's a good step in the right direction. Would be nice to get it working with Network Manager, but this reminds me of the good old days (when we upgraded our University's dial-up from SLIP to PPP and I had to figure out how to make it work with a distro based on the 0.99pl10 Linux kernel).

Initial Script
#!/bin/bash
# look for any Novatel Wireless device
VENDOR=1410
DEVICE=`lsusb |  grep $VENDOR | cut -d : -f 3`
# if a device exists, make sure it's the Virgin Mobile modem
# if it is the modem, make usbserial probe the device
if [ "${DEVICE:0:4}" != "6002" ];
    then echo Virgin Mobile card not found; exit 1
    else sudo modprobe usbserial vendor=0x$VENDOR product=0x$DEVICE;
fi
# make sure that usbserial created /dev/ttyUSBn device(s)
# if the USB tty is there, then initiate the ppp connection
TTYUSB=`ls /dev/ttyUSB*`
if [ -z "$TTYUSB" ];
    then echo No TTY created; exit 1
    else sudo wvdial;
fi

Saturday, October 27, 2007

More on bash, arrays, and index values

So, if you "man bash", you will see the following:
Arrays
Bash provides one-dimensional array variables. Any variable may be
used as an array; the declare builtin will explicitly declare an array.
There is no maximum limit on the size of an array, nor any requirement
that members be indexed or assigned contiguously. Arrays are indexed
using integers and are zero-based.
...
Any element of an array may be referenced using ${name[subscript]}.
...
${#name[subscript]} expands to the length of ${name[subscript]}. If subscript is * or @,
the expansion is the number of elements in the array.
...
The unset builtin is used to destroy arrays. unset name[subscript]
destroys the array element at index subscript. unset name, where name
is an array, or unset name[subscript], where subscript is * or @,
removes the entire array.
What does all that mean? It means that index values don't get reset when you unset array elements, so you shouldn't rely on ${#name[*]} in loops, unless you know that the index values are contiguous. So, if you want to loop based on the number of elements, you had better reset the index values by using something like: name=(`echo ${name[*]}`)

Copy and paste the following into a file, and then run it using your favorite implementation of bash (Cygwin, OS X, Linux, BSD, etc.) to see how it all works:
#!/bin/bash
function show_array {
echo There are ${#NUMBERS[*]} numbers in the array.
echo The index positions and values are:
IDX=0
while [ $IDX -lt ${#NUMBERS[*]} ]; do
echo -e $IDX \\t ${NUMBERS[$IDX]}
let IDX+=1
done
}
function pause () {
read -p "$*"
}
echo Bash Shell Array Element Index Handling
echo ----------------------------------------
NUMBERS=(zero one two three four five six seven eight nine)
show_array
pause "Press Enter "
echo ----
echo Now, let\'s unset number five, and see what happens...
unset NUMBERS[5]
show_array
echo Eek!, looks like there\'s a NULL element in there.
echo So, the number of elements has been reset, but the indexing has not.
echo Indexing is non-contiguous by design, so this isn\'t a bug. However,
echo this means that we do not get to see all of the elements if we are
echo looping based on the number of elements in the array.
pause "Press Enter "
echo ----
echo Let\'s try to unset number 1 this time...
unset NUMBERS[1]
show_array
echo Looks like there\'s another NULL element in there, now.
echo Again, the number of elements has been reset, but the indexing has not...
echo The \${#NUMBERS[*]} does not count NULLs, but index values do not
echo change. The while loop produces apparent garbage after some elements
echo have been unset.
pause "Press Enter "
echo ----
echo Enter the cheesy work-around:
echo "It looks like this: NUMBERS=(\`echo \${NUMBERS[*]}\`)"
echo This kills the NULL values and resets the indexing so it is
echo contiguous again...
NUMBERS=(`echo ${NUMBERS[*]}`)
show_array
Happy bash-ing...

Monday, October 15, 2007

Array Variables in bash

In my efforts to improve my NTFS-3G mount/re-mount script, I had to learn how to implement an array variable. Turns out it's painfully simple, and now I feel that I should go back and eradicate the evil temporary files that I used in some of my earlier quickly-generated scripts. But, I digress... Here are some quick basics that proved useful:
  • Array variables can be implicitly declared, e.g. PETS=(dog cat bird fish) builds a four-element array.
  • To show the whole array, use ${PETS[*]}
  • To show the number of elements in the array, use ${#PETS[*]}
  • Element index starts at zero so ${PETS[1]} will return cat
Here's the sample code that I threw together to make sure I figured it out properly, with comments added in a different font to explain each line of the script:
#!/bin/bash
# build an array of partitions (OS X), populated only with disk#s# for each partition
TEST=(`diskutil list | egrep disk.s. | awk '{print $NF}'`)
PARTS=0
# Build a menu that shows each partition in the array
# but start numbering at 1 instead of 0
while [ $PARTS -lt ${#TEST[*]} ]; do
let COUNT=PARTS+1
echo "$COUNT".\) ${TEST[$PARTS]}
let PARTS+=1
done
# Prompt for / grab user input, and see if it matches something on the menu
echo -n Please select a partition from the menu above:
read TRYIT
case $TRYIT in
[1-${#TEST[*]}])
# NOTE: [1-3]is an expression that matches 1, 2, or 3...
echo You typed a valid number: $TRYIT;;
*)
echo You typed a bad number: $TRYIT;
exit 100; # set a non-zero exit code
esac

Sunday, October 14, 2007

NTFS-3G Mount/Re-Mount Script for OS X

Requirements:
Features:
  • Optional Command-Line Parameters:
    • Partition to mount or re-mount (must be specified as the first parameter)
    • Use the force option at mount (can be specified as either first or 2nd parameter)
    • If no parameters are entered, script enters "interactive mode," and prompts user with a menu of confirmed NTFS partitions
  • Handle volumes that are currently using the (read-only) kernel NTFS driver
    • Prompt to unmount, custom exit level if user-aborted
    • Capture name that is assigned in Finder
    • Remount as read/write using the same Finder name
  • Handle volumes that are not currently mounted
    • Mount and assign a default Finder name: NTFS-disk#s#
  • Input Sanitizing
    • Volumes can be entered as "/dev/disk#s#" or (preferably) as "disk#s#"
    • Script throws custom exit level if volume does not exist
    • Script throws custom exit level if mount command fails due to non-NTFS volume
    • Script throws custom exit level if it encounters NTFS-3G errors during mount
  • (Possible Future Enhancements)
    • Add a -? or --help option to the script for über-completeness
    • Silent output -- rely only on the exit codes (Why? -- I can always redirect to /dev/null if I want to call it from within another script)
    • Something I haven't thought of yet...
  • bzip2 compressed version of the script (now includes updates through 1.4).
UPDATES
[Oct. 15] Version 1.1:
  • Implemented volume-unique mount points, so more than one disk can be mounted
  • Implemented menu (via array variable) for volume selection -- type a number instead of having to type disk#s#
[Oct. 16] Version 1.2:
  • Implemented actual type detection using File System field from "diskutil info disk#s#"
  • Previous method used reasonable speculation based on type field from "diskutil list"
  • Learned that array index values can be non-contiguous, and are not changed when array elements are unset. (This led to a later post.)
[Oct. 19] Version 1.3:
  • Added current mount point information to menu (yep, another array)
  • Added header bar to menu
  • Added Quit option to menu
[Oct. 27] Version 1.4:
  • Implemented the file system type detection for volumes that are input from the command line.
  • Previously, this was only implemented for volumes on the menu in "interactive mode."
  • Added an exit level for "Not an NTFS Volume."

Wednesday, August 22, 2007

Potential Mac Screen Properties Life-Saver

I managed to freak out the display settings for my screen that was set as the primary display (TV via the S-Video out adapter, because I was using Front Row, and didn't want to use mirror mode) on my notebook this morning by magically switching it to PAL and hitting OK while moving the notebook. [This particular maneuver requires a unique mix of uncanny bad luck coupled with a distinct lack of caffeination, and is neither likely to occur nor recommended.] Well, being an resident of the USA, said TV's S-Video input needed an NTSC signal, and so things were not exactly happy. Because of the way OS X puts the properties page for a given screen on that screen (which is normally nice) and because it also lacks a hot-key for moving a window, I was fairly hosed for a while.

Plugging back in my DVI monitor didn't help (separate settings were maintained on a per-device basis), and I simply couldn't find the darn settings anywhere in the Library or elsewhere... I got lucky, though, that monitor happened to have an S-Video input, and managed to sync with the 50Hz signal. That change in luck allowed me to reset the mode in which the TV adapter was running successfully. But, what would I do if I ever hosed something in an manner that was not so easily recoverable?

Enter cscreen, the hard-to-find (because the author abandoned it and his site) utility that allows modification of OS X display settings from the command line. I finally found it on the ScriptBuilders site, and am pleased to report that it works as designed -- allowing screen properties to be properly transmogrified from the command line. This even works from an SSH session, so now no amount of sleep and caffeine deprivation mixed with poor thumb placement can ever cause near-tragic screen gobbledy-gookage ever again...

Oh, yeah, this also makes it easy to switch which screen is the primary, and to rig up some scripts to switch among settings that I may want to use from time to time. Now, I still kinda want to find where these settings actually live, but that's a project for another time.