#!/bin/sh
#
# $Id: linkss 7138 2010-11-10 21:27:21Z NiLuJe $
#

# Pull some helper functions for logging
_FUNCTIONS=/etc/rc.d/functions
[ -f ${_FUNCTIONS} ] && . ${_FUNCTIONS}

linkss_die()
{
    msg "$1" W
    exit 0
}

is_integer() {
    [ "$1" -eq "$1" ] > /dev/null 2>&1
    return $?
}

LINKFONTS_BASEDIR="/mnt/us/linkfonts"

K2_SCREEN_SIZE="600x800"
KDX_SCREEN_SIZE="824x1200"

# And our actual screen size (from rc.d/functions)
MY_SCREEN_SIZE="${SCREEN_X_RES}x${SCREEN_Y_RES}"

LINKSS_BASEDIR="/mnt/us/linkss"
WATCHDOG_PID="${LINKSS_BASEDIR}/run/usb-watchdog.pid"
WATCHDOG_DAEMON="${LINKSS_BASEDIR}/bin/usb-watchdog"
WATCHDOG_HELPER="${LINKSS_BASEDIR}/bin/usb-watchdog-helper"

if [ -f ${LINKSS_BASEDIR}/backup ] ; then
    msg "backing up default screensavers" I
    # Just in case, create our backup dirs
    [ -d ${LINKSS_BASEDIR}/backups ] || mkdir ${LINKSS_BASEDIR}/backups
    for kx_size in ${K2_SCREEN_SIZE} ${KDX_SCREEN_SIZE} ; do
        [ -d ${LINKSS_BASEDIR}/backups/${kx_size} ] || mkdir ${LINKSS_BASEDIR}/backups/${kx_size}
    done

    # Huh, we asked for a backup!
    cp -f /etc/prettyversion.txt ${LINKSS_BASEDIR}/backups/prettyversion.txt

    # Handle both k2 & kDX
    for kx_size in ${K2_SCREEN_SIZE} ${KDX_SCREEN_SIZE} ; do
        [ -d /opt/amazon/screen_saver/${kx_size} ] && cp -f /opt/amazon/screen_saver/${kx_size}/* ${LINKSS_BASEDIR}/backups/${kx_size}/
    done

    # And do it only once ;)
    rm -f ${LINKSS_BASEDIR}/backup
fi

# Sanity check... Don't do anything if the screensavers dir is empty
[ -d ${LINKSS_BASEDIR}/screensavers -a "x$( ls -A ${LINKSS_BASEDIR}/screensavers 2> /dev/null )" != x ] || linkss_die "we don't have any custom screensavers, aborting"

# Clean our custom screensavers directory to avoid weird bugs
# Let's delete the Windows thumbs.db file if it's there.
[ -f ${LINKSS_BASEDIR}/screensavers/thumbs.db ] && rm -f ${LINKSS_BASEDIR}/screensavers/thumbs.db
# Or windows folder config file if it's there.
[ -f ${LINKSS_BASEDIR}/screensavers/Desktop.ini ] && rm -f ${LINKSS_BASEDIR}/screensavers/Desktop.ini
# And mac's folder config file.
[ -f ${LINKSS_BASEDIR}/screensavers/.DS_Store ] && rm -f ${LINKSS_BASEDIR}/screensavers/.DS_Store
# And those pesky mac ._ files.
for macthumb in ${LINKSS_BASEDIR}/screensavers/._* ; do
    [ -f "${macthumb}" ] && rm -f "${macthumb}"
done

# Randomize screensavers if we asked for it
if [ -f ${LINKSS_BASEDIR}/random ] ; then
    msg "start of screensavers randomizing" I

    # Randomly sort our screensavers
    [ -x ${LINKSS_BASEDIR}/bin/sort ] || chmod +x ${LINKSS_BASEDIR}/bin/sort
    sort_index=1

    # Loop through all our sorted custom screensavers, and rename them in order (order that's now random, courtesy of coreutils' sort),
    # with a fixed-length zero-padded index as a prefix, ie. ${id}_my_super_image.png instead of my_super_image.png
    IFS_BKP="${IFS}"
    # We use an invalid character for FAT32 filenames to avoid any problem, because the Kindles crappy shell doesn't like NULL as an IFS...
    IFS=':'
    # NOTE: There's some fairly ugly IFS trickery involved in order to work with filenames containing spaces, because we can't rely on the proper
    # methods available to fix this in a real shell...
    for ss_file in $( find ${LINKSS_BASEDIR}/screensavers -type f -print0 | ${LINKSS_BASEDIR}/bin/sort -R -z | tr '\0' ':' ) ; do
        # Not a file? NEEEEXT!
        [ -f "${ss_file}" ] || continue

        # Handle the zero-padding of our index, to make sure it's always the same length. (to make non natural order sorting algorithms happy)
        zero_pad=""
        for pad_step in 10000 1000 100 10 ; do
            if [ ${sort_index} -ge ${pad_step} ] ; then
                ss_new_idx="${zero_pad}${sort_index}"
            else
                zero_pad="${zero_pad}0"
                ss_new_idx="${zero_pad}${sort_index}"
            fi
        done

        # First, get the basename of our files
        ss_filename="${ss_file##*/}"

        # Then, try to extract the current index of our file
        ss_idx="${ss_filename%%_*}"

        # Check if it's really an int, to see if this is the first randomizer round...
        if is_integer ${ss_idx} ; then
            # We've already got an index, ditch it, and retrieve our original real filename
            ss_real_filename="${ss_filename##${ss_idx}_}"
        else
            # First run, our full name is our real name
            ss_real_filename="${ss_filename}"
        fi

        # And rename our files
        [ "${ss_filename}" != "${ss_new_idx}_${ss_real_filename}" ] && mv -f "${LINKSS_BASEDIR}/screensavers/${ss_filename}" "${LINKSS_BASEDIR}/screensavers/${ss_new_idx}_${ss_real_filename}"

        # Increment our index
        sort_index=$(( sort_index + 1 ))
    done
    # Restore IFS
    IFS="${IFS_BKP}"
    msg "end of screensavers randomizing" I
fi

# Handle both k2 & kDX
for kx_size in ${K2_SCREEN_SIZE} ${KDX_SCREEN_SIZE} ; do
    # If it's not our actual screen size, skip
    if [ "${kx_size}" != "${MY_SCREEN_SIZE}" ] ; then
        msg "our screen resolution isn't ${kx_size}, skipping" I
        continue
    fi
    # Make sure that size is actually valid on our system, in case we got a buggy screen size var
    if [ -d /opt/amazon/screen_saver/${kx_size} ] ; then
        # Don't mount twice & handle crashes... We may have a leftover mount state file
        if ! grep "^fsp /opt/amazon/screen_saver/${kx_size}" /proc/mounts > /dev/null 2>&1 ; then
            msg "mounting custom screensavers (${kx_size})" I
            mount --bind ${LINKSS_BASEDIR}/screensavers /opt/amazon/screen_saver/${kx_size}

            # Let our stop script know that we've got things to unmount
            touch ${LINKSS_BASEDIR}/mounted_${kx_size}
        else
            msg "looks like the custom screensavers (${kx_size}) are already mounted" W
        fi
    fi
done

# If needed (ie. hack applied, and linkfonts watchdog not already up), launch our litle usb unplug watchdog
if [ -f ${LINKSS_BASEDIR}/mounted_${K2_SCREEN_SIZE} -o -f ${LINKSS_BASEDIR}/mounted_${KDX_SCREEN_SIZE} ] ; then
    # Launch our little watchdog to catch the usb unplug event, but make it optionnal (and don't launch it if linkfonts' already up)
    if [ -f ${LINKSS_BASEDIR}/autoreboot -a ! -f ${LINKFONTS_BASEDIR}/autoreboot ] ; then
        # Avoid running multiple watchdogs by cleanup up somewhat forcefully...
        # Handle crashes, and runlevel switches... We may have a leftover pidfile with stale pids, so take care of it ourselves (start-stop-daemon doesn't check if the daemon's alive)
        if [ -f ${WATCHDOG_PID} ] ; then
            for pid in $( cat ${WATCHDOG_PID} ) ; do
                # If we do indeed have one, then check it's content, and kill everything pertaining to the watchdog, to avoid having part of the trio running without the others
                if ps -fp ${pid} | grep -e "${WATCHDOG_DAEMON}" -e "usbPlugOut" -e "${WATCHDOG_HELPER}" > /dev/null 2>&1 ; then
                    msg "killing stale USB watchdog (${pid})" W
                    kill -KILL ${pid} 2> /dev/null
                fi
            done
            # And then remove the pidfile
            rm -f ${WATCHDOG_PID}
        fi
        # Make sure our watchdog scripts are there
        if [ -f ${WATCHDOG_DAEMON} -a -f ${WATCHDOG_HELPER} ] ; then
            # Make sure they're executable
            [ -x ${WATCHDOG_DAEMON} ] || chmod +x ${WATCHDOG_DAEMON}
            [ -x ${WATCHDOG_HELPER} ] || chmod +x ${WATCHDOG_HELPER}
            # And finally, run it
            msg "launching usb watchdog" I
            /sbin/start-stop-daemon -m -q -p ${WATCHDOG_PID} -x ${WATCHDOG_DAEMON} -S -b
        fi
    fi
fi

# Do we want a custom version tag?
if [ -f ${LINKSS_BASEDIR}/etc/prettyversion.txt ] ; then
    # Don't mount twice & handle crashes... We may have a leftover mount state file
    if ! grep "^fsp /etc/prettyversion.txt" /proc/mounts > /dev/null 2>&1 ; then
        msg "mounting custom version tag" I
        mount --bind ${LINKSS_BASEDIR}/etc/prettyversion.txt /etc/prettyversion.txt

        # Let our stop script know that we've got things to unmount
        touch ${LINKSS_BASEDIR}/ver_mounted
    else
        msg "looks like a custom version tag is already mounted" W
    fi
fi
