#! /bin/sh

set -e

if [ "$(blkid | grep -c ^/dev/mapper)" != "0" ]
then
    DISKDRIVE=$(/bin/mount | grep "on /boot type" | awk '{print $1}' | tr -d '0-9')
else
    DISKDRIVE=$(/bin/mount | grep "on / type" | awk '{print $1}' | tr -d '0-9' | grep -v ^/dev/mapper)
fi

if [ "${DISKDRIVE}" != "" ]
then
    [ -x /sbin/hdparm ] && [ "$(/sbin/hdparm -I "${DISKDRIVE}" | grep -c 'TRIM supported')" = "1" ] || exit 0
else
    exit 0
fi

[ -x /sbin/fstrim ] || exit 0

if which on_ac_power >/dev/null 2>&1 
then
    ON_BATTERY=0
    on_ac_power >/dev/null 2>&1 || ON_BATTERY=$?
    if [ "${ON_BATTERY}" -eq 1 ]
    then
	exit 0
    fi
fi

##

LOCKFILE="/var/lock/fstrim.lock"

trap 'rm -f ${LOCKFILE}' EXIT

if [ -e "${LOCKFILE}" ]
then
    echo >&2 "Warning: ${LOCKFILE} present, not running fstrim."
    exit 1
else
    touch "${LOCKFILE}"
fi

##

# See ionice(1)
if [ -x /usr/bin/ionice ] && /usr/bin/ionice -c3 true 2>/dev/null
then
    IONICE="/usr/bin/ionice -c3"
fi

if [ "$(/bin/mount | grep "on / type" | awk '{print $1}' | grep -c ^/dev/mapper)" = "1" ]
then
    DISKDEV=$(/bin/mount | grep "on /boot type" | awk '{print $1}' | cut -d "/" -f3 | tr -d '0-9')
else
    DISKDEV=$(/bin/mount | grep "on / type" | awk '{print $1}' | cut -d "/" -f3 | tr -d '0-9')
fi

#CUTOFFHERE
if [ -b "/dev/${DISKDEV}" ] && [ "$(cat /sys/block/"${DISKDEV}"/queue/rotational)" = "0" ]
then
    cat << EOFONE

You will receive this message only once:

Window Maker Live is installed on an SSD, for which the TRIM feature
has been activated. If the following output does not contain an error
message claiming "FITRIM ioctl failed", but just displays the amount
of discarded blocks per mounted filesystem, then it simply works:

--- snip ---
EOFONE
    for filesys in $(/bin/mount | grep " type " | grep -E 'ext4|ext3|xfs'| awk '{print $3}')
    do
        ${IONICE} fstrim -v "${filesys}"
    done

    SUCCESSRATE="${?}"

    if [ "${SUCCESSRATE}" = "1" ]
    then
        cat << EOFTWO
--- snip ---

Unfortunately, TRIM appaears not to be supported for your SSD. Since there
is no point periodically running "$0", it was disabled.

EOFTWO
    elif [ "$SUCCESSRATE" = "0" ]
    then
    cat << EOFTHREE
--- snip ---

As can be seen above, TRIM appears to be properly working for your SSD.

From now on, while not running on battery, anacron executes the script
"$0" on a daily basis.

You will not receive any further mails in this regard.

EOFTHREE
    fi
fi
sed -n '/\#CUTOFFHERE/q;p' < "$0" | sed 's/\#set\ \-e/set\ \-e/' > /tmp/$(basename "$0").$$

if [ -s /tmp/$(basename "$0").$$ ]
then
    cat >> /tmp/$(basename "$0").$$ << "EOFENTRY"
if [ -b "/dev/${DISKDEV}" ] && [ "$(cat /sys/block/"${DISKDEV}"/queue/rotational)" = "0" ]
then
    for filesys in $(/bin/mount | grep " type " | grep -E 'ext4|ext3|xfs'| awk '{print $3}')
    do
        ${IONICE} fstrim "${filesys}"
    done
fi
EOFENTRY
fi

cat /tmp/$(basename "$0").$$ > "$0" && rm -f /tmp/$(basename "$0").$$
