Mint Serena 64 bit using the Mate desktop environment. Most of the following scripts will run on this machine, although some have only been tested with the Gnome desktop. Extra software requirements can be met by the Ubuntu and safe PPA repositories. Scripts may be re-written or added to from time to time, the date serves as the version number. Syntax highlighting on these pages is provided by GVim's "Convert to HTML" option.
Showing posts with label utility. Show all posts
Showing posts with label utility. Show all posts

Weather Scraper


#!/bin/bash
# Filename: weather.sh
# Version.: 21092018
# Author..: robz
#
# Met Office scraper widget.
# Get the url from the web page for your location, chop the date off the end.
# Run from a launcher with this command.
# mate-terminal -t "Current Weather" -e /home/robz/scripts/weather.sh
#
sed1 () { sed 's/<[^>]\+>//g'; }
sed2 () { sed -e 's/^[ \t\n]*//;s/[ \t\n]*//'; }

wsite="https://www.metoffice.gov.uk/public/weather/forecast/qwerty123#?date="
wfile="/home/robz/scripts/weather.txt"
hours=$(date +%H | sed 's/^0//')
today="$(date +%Y-%m-%d)"
check=$(grep 'Timecheck' "$0" | tail -1 | cut -d' ' -f3)

if [[ "$check" != "$hours" ]]; then             # Check stamp at end of script.
    wget -q --retry-connrefused --waitretry=1 \
    "$wsite$today" -O "$wfile"                  # If it's old re-scrape page.
    sed -i '$d' "$0"                            # Delete old time stamp.
    echo "# Timecheck $hours" >> $0             # Insert new.
fi

echo -e "\nTodays weather - $(date +%a' '%d' '%b' - '%H':00') onwards:-\n"

time=$(grep -m1 -A9 'Now' "$wfile" | sed1 | sed2)
aspt=$(grep -m1 -A30 'weatherWX' "$wfile" | sed2 | grep 'title' | \
cut -d\" -f2 | sed -e 's/day\|night//')
prec=$(grep -m1 -A10 'Chance' "$wfile" | sed1 | sed2 | cut -d\; -f2 | tail)
temp=$(grep -m1 -A80 'weatherTemp' "$wfile" | grep 'data-value=' | \
cut -d\" -f2 | sed 's/$/°C/')
wind=$(grep -m10 -A10 '"direction"' "$wfile" | grep 'data-value=' | \
cut -d\" -f2 | sed -e 's/$/mph/')
win2=$(grep -m10 -A10 '"direction"' "$wfile" | grep 'data-value2=' | \
cut -d\" -f2)
gust=$(grep -m11 -A11 '"gust"' "$wfile" | grep 'data-value="' | sed 'n;d;' | \
cut -d\" -f2 | sed -e 's/$/mph/')

hours=$(( 24-hours ))                           # Number of hours to head file.
paste <(echo "$time") <(echo "$aspt") <(echo "$prec") <(echo "$temp") \
<(echo "$wind") <(echo "$win2") <(echo "$gust") | head -n$hours | \
column -s $'\t' -t

echo
echo $(grep -m2 -E 'Sunrise|Sunset' "$wfile" | sed1 | sed2) | column -s -t
read

# Timecheck has to be the last line no blanks.
# Timecheck 13

Clean Scrape


#!/bin/bash
# Filename: clean-scrape.sh
# Version.: 05082018
# Author..: robz
# Clean list of magnet links from "showRSS.info" page source scrape.
# Add to your file browser scripts directory for right click usage.
# Usage: In the web browser, right click - "View Page Source" - "Select All" 
# left click - drag to desktop - right click - run script

cd '/home/robz/Desktop'
[ -e 'dropped text.txt' ] || exit
sed '/1080p\|720p/d;/href="magnet/!d;s/.*href="//;s/" .*//' 'dropped text.txt' \
| sort -t= -k3 -o 'dropped text.txt'
mv 'dropped text.txt' 'add-magnet.txt'
exit

Fix Subtitle Offset


#!/bin/bash
# Filename: srt-fix-offset.sh
# Version.: 20052018
# Author..: not robz
# A script to modify subtitle offset beyond the Kodi maximum of 60 seconds.
# Put original titles in a file called "srt.txt" in your home directory and
# run the script.
# In all honesty this is pretty much a copy paste job from Linux Questions.
# For more detailed information goto:
# www.linuxquestions.org/questions/linux-newbie-8/editing-srt-files-4175436550/
#
# Modify and comment the offset variable as appropriate.
# Advance subtitles.
offset="75 seconds"
# Retard subtiles.
#offset="5 seconds ago"

while read start s end; do
    if [[ $start =~ ^..:..:..,... ]]; then
        start=$(date -d "$start $offset" +%H:%M:%S,%N)
        end=$(date -d "$end $offset" +%H:%M:%S,%N)
        echo ${start:0:12} $s ${end:0:12}
    else
        echo $start $s $end
    fi
done < srt.txt >> new-subtitles.srt

Morse 2


#!/bin/bash
# Filename: morse2.sh
# Version.: 03102017
# Author..: robz
# Enter words hear morse.

trap 'kill -9 $pid 2>/dev/null; echo; exit' TERM EXIT

declare -A morse
morse[A]=".-"     morse[B]="-..."   morse[C]="-.-."   morse[D]="-.."
morse[E]="."      morse[F]="..-."   morse[G]="--."    morse[H]="...."
morse[I]=".."     morse[J]=".---"   morse[K]="-.-"    morse[L]=".-.."
morse[M]="--"     morse[N]="-."     morse[O]="---"    morse[P]=".--."
morse[Q]="--.-"   morse[R]=".-."    morse[S]="..."    morse[T]="-"
morse[U]="..-"    morse[V]="...-"   morse[W]=".--"    morse[X]="-..-"
morse[Y]="-.--"   morse[Z]="--.."   morse[1]=".----"  morse[2]="..---"
morse[3]="...--"  morse[4]="....-"  morse[5]="....."  morse[6]="-...."
morse[7]="--..."  morse[8]="---.."  morse[9]="----."  morse[0]="-----"
morse[.]=".-.-.-" morse[,]="--..--" morse[?]="..--.."

while true; do
    read -p "Input a word or sentence: " input
    echo
    while read -n1 character; do
        character="${character^^}"
        if [ "$character" ]; then
            echo -ne " $character\t"
            while read -n1 dotdash; do
                tput bold
                [ "$dotdash" = "." ] && duration="0.2" || duration="0.4"
                echo -n "$dotdash"
                (speaker-test -t sine -f 400 >/dev/null) & pid="$!";\
                sleep "$duration"; kill -9 "$pid"
                tput sgr0
            done < <(echo -n "${morse[$character]}")
            sleep 0.2; echo
        else sleep 0.4; echo
        fi 2> /dev/null
    done < <(echo -n "$input")
    echo
done

Morse


#!/bin/bash
# Filename: morse.sh
# Version.: 01102017
# Author..: robz
# Training aid to print out and recite morse code in a terminal.
# Get stuff "sudo apt install espeak"

tabs="\n"
code=(A .- B -... C -.-. D -.. E . F ..-. G --. H .... I .. J .--- K -.- \
L .-.. M -- N -. O --- P .--. Q --.- R .-. S ... T - U ..- V ...- W .-- X -..- \
Y -.-- Z --.. 1 .---- 2 ..--- 3 ...-- 4 ....- 5 ..... 6 -.... 7 --... 8 ---.. \
9 ----. 0 ----- stop .-.-.- comma --..-- query ..--..)

trap 'kill -9 $pid 2>/dev/null; exit' TERM EXIT

for character in {0..78..2}; do
    echo -ne "$tabs ${code[character]}\t"
    espeak -a 400 "${code[character]}"
    tput bold
    while read -n1 dotdash; do
        [ "$dotdash" = "." ] && duration="0.2" || duration="0.4"
        echo -n "$dotdash"
        (speaker-test -t sine -f 400 >/dev/null) & pid="$!";\
        sleep "$duration"; kill -9 "$pid"
    done < <(echo -n "${code[((character+1))]}")
    tput sgr0
    [ "$tabs" = "\n" ] && tabs="\t|\t" || tabs="\n"
    sleep 1
done 2> /dev/null
echo -e "\n\nEnd of morse code demo.\n"

exit

Raspberry Pi SSH


#!/bin/bash
# Filename: motd.sh
# Version : 23072017
# Author  : robz
# Raspberry Pi landing page SSH login script.
# Place this file in /etc/profile.d/ and set the executable bit.
# Interactive message of the day to display on secure shell login.
# It provides commands for control of "new-pvr.sh" PVR script.
# Add an alias to your .bashrc to call "motd.sh" info and menu.
# alias 1='/etc/profile.d/motd.sh'
# Then execute ". ~/.bashrc"

sudo killall -qg countLED.sh >/dev/null 2>&1

printf "\033c"
re="$(tput setaf 1)"; gr="$(tput setaf 2)"; ye="$(tput setaf 3)"
bl="$(tput setaf 4)"; mg="$(tput setaf 5)"; cy="$(tput setaf 6)"
gy="$(tput setaf 7)"; wh="$(tput setaf 9)"
myip="$(ifconfig eth0 | awk '/inet/{print $2}' | cut -d: -f2)"
boot="$(date -d "@"$(awk '/btime/{print $2}' /proc/stat) +"%d/%m/%y at %H:%M")"
last="$(last -i $(whoami) | awk 'NR==2 {print $1,$3,$4,$5,$6,$7}')"
uptm="$(awk '{print int($1/86400)" days, "int($1%86400/3600)" hours, "int($1%3600/60)" minutes"}' /proc/uptime)"
memo="$(free -m | awk 'NR==2 {print "Total: "$2"MB, Used: "$3"MB, Free: "$4"MB"}')"
free="$(df -h ~ | awk 'NR==2 {print "Total: "$2"B, Used: "$3"B, Free: "$4"B"}')"
stor="$(df -h /dev/sda1 | awk 'NR==2 {print "Total: "$2"B, Used: "$3"B, Free: "$4"B"}')"
temp="$(/opt/vc/bin/vcgencmd measure_temp | cut -c "6-9")ºC"
sess="$(cat /home/pi/Downloads/log/motd.txt)"
tput bold
printf "$bl""%`tput cols`s" | tr ' ' '_'
echo "$gr
    .~~.   .~~.
   '. \ ' ' / .'  $re
    .~ .~~~..~.   $re     Raspberry Pi$wh Torrent Box$re
   : .~.'~'.~. :  $wh     a.k.a. pi@$myip$re
  ~ (   ) (   ) ~ $wh     on robz home network.$re
 ( : '~'.~.'~' : )$wh     Welcome back! login: $(whoami)$re
  ~ .~ (   ) ~. ~ $wh     $(date +"%A %d %b %Y %H:%M")$re
   (  : '~' :  )  $wh     $(echo Kernel $(uname -ro))$re
    '~ .~~~. ~'
        '~'
$ye Last Login....:$bl $last
$ye Last boot.....:$bl $boot
$ye Uptime........:$bl $uptm
$ye Memory........:$bl $memo
$ye Home space....:$bl $free
$ye USB storage...:$bl $stor
$ye Temperature...:$bl $temp
"
tput sgr0
echo "$wh$sess"
echo
echo -e " User PVR commands, the \"#\" or \"Enter\" for a shell prompt.\n\
 1) - Display this \"motd\" message. \
 2) - Nano edit add-magnet.txt.\n\
 3) - View today's session log.    \
 4) - Nano edit followed-shows.txt.\n\
 5) - List recently downloaded.    \
 6) - List the \"Watch\" directory.\n\
 7) - View rss-today.txt file.     \
 8) - Run \"TED Talks\" downloader."

tput bold
printf "$bl""%`tput cols`s" | tr ' ' '_'
read -n1 n
printf "\033c"
case $n in
    1) /etc/profile.d/motd.sh;;
    2) nano ~/Downloads/scripts/add-magnet.txt;;
    3) cat ~/Downloads/log/"$(date +%a-%-d%b)"*runlog.txt; read -n1;;
    4) nano ~/Downloads/scripts/followed-shows.txt;;
    5) echo -e "\nRecently Downloaded\n"
    tac ~/Downloads/log/rec.txt; read -n1;;
    6) echo -e "\nTrackers in \"Watch\" directory\n"
    ls Downloads/Watch; read -n1;;
    7) cat ~/Downloads/log/rss-today.txt; read -n1;;
    8) /home/pi/Downloads/scripts/ted-talks.sh; read -n1;;
   "") killall motd.sh;;
esac
/etc/profile.d/motd.sh

# Add this alias to your .bashrc to call "motd.sh" info and menu.
# alias 1='/etc/profile.d/motd.sh'
# Then execute ". ~/.bashrc"


Timer Mk3


#!/bin/bash
# Filename: progbar-timer.sh
# Version.: 19042017
# Author..: robz
# What another one!
# Improved from the "Egg Timer" script, a countdown timer with progress bar.
# This one has an indication of time remaining provided by Zenity's progress
# bar function. You'll need to choose a sound file below and maybe fiddle with
# the vector_tl function x&y coordinates.

vector_tl ()                                              # Dialog to top left.
{
x="541"; y="315"
until [ "$x" -lt "0" ]; do
    wmctrl -r "Egg Timer Mk3" -e 0,"$x","$y",210,129
    ((x-=30)); ((y-=18))
done
}

count=$(zenity --title "Egg Timer Mk3" --text "Decimals allowed Min/Hrs"\
    --entry-text "eg. 10s or 5m or 2h" --entry)           # Input dialogue.
if [ $? = 1 ]; then exit $?; fi

# Determine number of seconds to count down from depending on input suffix.
case "${count: -1}" in
    "S" | "s" ) count=$(echo ${count%?}/1 | bc) ;;
    "M" | "m" ) count=$(echo ${count%?}*60/1 | bc) ;;
    "H" | "h" ) count=$(echo ${count%?}*3600/1 | bc) ;;
    *         ) zenity --error --text "<span color=\"red\"><b>\
    \nUse the form of 10s or 5m or 2h\nDecimals allowed Min/Hrs.</b></span>"
    sh -c "$0"                                            # On error restart.
    exit ;;
esac

(sleep 1 && vector_tl) &

start=$count                                              # Set a start point.

until [ "$count" -eq "0" ]; do                            # countdown loop.
    ((count-=1))                                          # Decrement seconds.
    percent=$((100*count/start))                          # Calc percentage.
    echo "#Time remaining:$(echo "obase=60;$count" | bc)" # Convert to H:M:S.
    echo $percent                                         # Outut for progbar.
    sleep 1
done | zenity --title "Egg Timer Mk3" --progress --percentage=0 --text=""\
    --auto-close                                          # Progbar/time left.

if [ $? = 1 ]; then exit $?; fi
zenity --info --title "Egg Timer Mk3" --text "## TIMES UP ##" &
play $HOME/Scripts/glass_ping.wav                         # Ping sound finish!
vector_tl
exit


Cooler CPU


#!/bin/bash
# Filename: cpulimit-ghb.sh
# Version.: 09032017
# Author..: robz
# I know, I'm cheap, I should buy a better than stock cooling fan, but....
# Dynamically use the cpulimit utility to keep cpu within a sane temperature
# range when using Handbrake or another resource hammering program.
# sudo apt install cpulimit lmsensors - use PPA for the latest Handbrake.
# Dependant on the output of "sensors" you may need to tweak line ##.

if [ "$UID" != "0" ]; then                          # Get root privilege.
    sudo -k; exec gksudo --message "$(echo\
    'Enter your password please, you need root';\
    echo 'privileges to run cpulimit effectively.')"\
    "$0"
fi

max='67'                                            # Maximum temperature°C.
cores='2'                                           # Number of cpu cores.
prog='/usr/bin/ghb'                                 # Program you're limiting.
limit=$((100*cores))                                # Total 100% limit range.
base="$limit"

while [[ "$(pidof "$prog")" ]]; do
    temp=$(sensors | grep 'CPU:' | cut -c18-19)     ## Get cpu temperature.
    if [[ "$temp" -gt "$max" && "$limit" -gt '25' ]]; then
        killall /usr/bin/cpulimit                   # Kill old process.
        ((limit-=25))                               # Increment limit down.
        cpulimit -qb -P "$prog" -l "$limit"         # Start new process.
    elif [[ "$temp" -lt "$max" && "$limit" -lt "$base" ]]; then
        killall /usr/bin/cpulimit
        ((limit+=25))                               # Increment limit up.
        cpulimit -qb -P "$prog" -l "$limit"
    fi
    sleep 5
done

killall /usr/bin/cpulimit
exit


New PVR


#!/bin/bash
# Filename: new-pvr.sh
# Version.: 03042018
# Author..: robz
# WARNING! this works on my system it may break yours, read, check, tweak #####
# A torrent box script for a headless Raspberry Pi model B, it auto downloads
# media files for show episodes followed, then renames and transfers to NAS.
# Required software: xmllint, transmission-daemon and transmission-cli.
# Enable the "Watch" and "Incomplete" directories in transmission-daemon's
# settings.json, this can also be done using the web interface.
# http://<your-pi's-net-address-192.168.0.etc>:9091/transmission/web/#all
# No login required no gui, just power up pi whenever or leave on all the time.
# Downloads will occur at random times 01:00-05:00 ie. during off peak hours.
# List show names in the "followed-shows.txt" file one entry per line.
# Manually added links are copy/pasted to the "add-magnet.txt", one per line.
# Make script executable and run it first in /home/<user> i.e. ./new-pvr.sh
#
# Add to "sudoers" with sudo visudo, this, "pi ALL=(ALL) NOPASSWD: ALL". ######
# Backup your "/etc/fstab" then add these lines, leave out "#" on second line
# Allow mount of network drive using the samba protocol, but without sudo.
#//192.168.<etc>/Media  /home/pi/Media  cifs  guest,uid=pi,noauto,user  0  0
# Alter the NAS address (first one) to suit your network.

# Create a "Downloads" directory in home before running the script.
cd "$HOME/Downloads" || exit                        # Go to working directory.
# If script fails kill processes allowing cron to do a reboot.
trap "killall -q transmission-daemon; exit" SIGINT SIGTERM SIGHUP EXIT

# Setup variables.
smb="$HOME/Media/Cloud TV"                          # Samba mount point to NAS.
trk="$HOME/.config/transmission-daemon"             # The daemon's config file.
add='scripts/add-magnet.txt'                        # Any extra magnet links.
don='scripts/done-shows.txt'                        # Done downloads list.
rss='scripts/rss.txt'                               # Feed file rss listing.
rlg='log/run.log'                                   # This session, statistics.
dlg='log/debug.log'                                 # Debug log.
rec='log/rec.txt'                                   # Recently downloaded list.
mod='log/motd.txt'                                  # Message for ssh login.
ret='3'                                             # File retention in days.
cdn='0'                                             # Count/countdown variable.
export trk                                          # Give access for subshell.
###############################################################################
# On first run, this part of the script creates the directory/file structure 
# in /pi/Downloads, it also installs the random time run-script crontab.
if [ ! -e scripts/"$(basename $0)" ]; then
    set -o noclobber
    mkdir "/home/pi/Media"
    mkdir -p {Complete,Incomplete,scripts,log,ted}
    &> /dev/null > scripts/followed-shows.txt
    &> /dev/null > scripts/clipboard.txt
    &> /dev/null > scripts/recent.txt
    &> /dev/null > "$add"
    &> /dev/null > "$don"
    &> /dev/null > "$rss"
    t0='# Randomly between 01:00 and 05:00 new-pvr.sh run it.'
    t1='00 00 * * * /bin/sleep $(((RANDOM\%10800)+3600)); '
    t2="/home/pi/Downloads/scripts/$(basename $0); sudo shutdown -r +1"
    (crontab -u "$USER" -l; echo -e "\n$t0\n$t1$t2\n" ) | crontab -u "$USER" -
    cp "$0" scripts; mv "$0" "$0".backup
    echo 'Now add some shows to the followed-shows.txt'
    exit
else
    echo '### Files exist, no action taken ###'
fi
# On subsequent runs it does nothing, you can delete it if you like.
# NB. I noticed after my OS ugrade this section throws an error message, but it
# still seems to do it's job, so check file structure is in place before use.
###############################################################################
# Set up log files. 
mv "$dlg" "log/$(date -d y +%a-%-d%b)-debug.log"    # Rename old debug log.
mv "$rlg" "log/$(date -d y +%a-%-d%b)-run.log"      # Rename old session log.
set -x                                              # Generate debug output.
exec > "$dlg" 2>&1                                  # Route debug to debug.log.
date > "$rlg"                                       # Start a new session log.
> "$mod"                                            # Blank motd.txt.
# Timer will wait for "Incomplete" to empty or for a file to appear dependant
# on whether the $swh variable is set or not, or it'll just time out.
run_timer () {
while [ "$cdn" -gt "1" ]; do
    [[ ! "$swh" && "$(ls Incomplete)" ]] && break
    [[ "$swh" && ! "$(ls Incomplete)" ]] && break
    (( cdn-=5 )); sleep 5
done 2> /dev/null
}
# Strip unwanted characters from filenames, magnet links and xml input.
# 's/s[0-9]*e[0-9]*/\U&/;'\
strip_title () {
sed -e \
's/\([S][0-9]*[E][0-9]*\).*\<.*/\1/;'\
's/.*>//;'\
's/[.+-]/ /g;'\
's/ \+/ /g;'\
's/.*dn=//;'\
's/New.*: //;'\
's/www Torrenting com //;'\
's/www scenetime com //'
}
# Remove links with no proper episode number or with episode number 00.
no_specials ()
{
strip_title <<< "$lnk" | grep 'E[0-9][0-9]' | grep -v 'E00'
}
# Housekeeping, clean up old downloads and logs.
[ "$(df --output=pcent / | sed '1d' | cut -d'%' -f1)" -gt 70 ] && ret="1"
find log -mtime +14 -type f -delete
find Complete -mindepth 1 -mtime +"$ret" -delete
find "$trk" -mtime +"$ret" -name *.torrent -type f -delete -execdir bash -c\
    'del="{}"; del="${del##*/}"; rm -f "$trk/resume/${del%.*}.resume"' \;
# Fire up dat daemon.
transmission-daemon -g "$trk"
echo "$(date +%T) - Transmission-daemon started." >> "$rlg"
sleep 60
# Download rss feeds, pretty print to seperate lines allowing parsing.
wget -q -O - 'https://showrss.info/other/all.rss' | \
xmllint --format - > "$rss" 2> /dev/null
cat scripts/clipboard.txt >> "$rss"                 # Append earlier download.
# Check followed-shows list against new rss.txt file, standard def. not HD. If
# you want HD versions you'll have to modify the "sed" statments, alternatively
# you could use the "add-magnet.txt" file for a one off.
## NB. GNU sed is being used in this script, BSD/POSIX versions won't do.  ####
if [ -s "$rss" ]; then
    while read -r shw; do
        if [[ "${shw:0:1}" != "#" && "$shw" != "" ]]; then
            epi=$(sed -n "/720p\|1080p/d;/descrip.*\b$shw/Ip" "$rss")
            [ -z "$epi" ] && continue
            while read -r lnk; do
                if ! grep -iq "$(strip_title <<< "$lnk")" "$don"; then
                    lnk="$(sed 's/.*href=\"//;s/\".*//' <<< "$lnk")"
                    if no_specials; then
                        echo "$lnk" >> "$add"
                        strip_title <<< "$lnk" >> "$don"
                    fi
                fi
            done <<< "$epi"                         # Add to add-magnet.txt
        fi
    done < 'scripts/followed-shows.txt'
    sed 's/.*E\([0-9][0-9]*\)/\1 &/' "$add" | sort -u -o "$add"
    sed -i 's/.* //' "$add"
    #sort -t "=" -k3 -u -o "$add" "$add"
    grep "raw.*title" "$rss" | sed "/720\|1080/d" | strip_title | sort -u \
    > log/rss-today.txt
else
    echo 1 > log/flashred.txt
    echo ' ## ERROR - rss feed failed to download. ##' | tee -a "$rlg" "$mod"
    > log/rss-today.txt
fi
# Load the bit torrent client with links from the "add-magnet.txt" file.
while read -r lnk; do
    [ "$cdn" -ge "3" ] && break
    (( cdn+=1 ))
    transmission-remote --add "$lnk"
    strip_title <<< "$lnk" >> "$don"
    sed -i '1,1d' "$add"
done < "$add"
sort -u "$don" -o "$don"                            # Tidy up done-shows list.
# Wait for first link to load, skip if incomplete files exist.
[ "$cdn" -ne "0" ] && \
(echo "$(date +%T) - Wait for links or resume incompletes." >> "$rlg";
cdn="420"; swh=""; run_timer)                       # Set to wait for link load.
# If torrents are present start session timer.
if [ "$(ls Incomplete)" ]; then
    transmission-remote --torrent all --start
    cdn="3600"; swh="1"
    echo "$(date +%T) - Proceeding with download $((cdn/60))m max." >> "$rlg"
    run_timer
    echo "$(date +%T) - Seed for another 10 minutes." >> "$rlg"
    sleep 600
    transmission-remote --torrent all --stop
    transmission-remote --session-stats | sed '3,6!d' >> "$rlg"
    (
    echo "$(date +%T) - End of $(date +%A)'s downloads."
    [ "$(ls Incomplete)" ] && echo 'Incomplete download(s):' && ls Incomplete
    ) >> "$rlg"
    echo " PVR session...: $(awk '/Downloaded/{print $1,$2$3}' "$rlg")" >>"$mod"
    echo 'Rename & transfer to network storage.' >> "$rlg"
fi
transmission-remote --exit
# Just the main video files are selected ignoring previews and promos.
# Create directories if needed on NAS and copy files there, renaming on the way.
cdn=0; new="$(find Complete -size +50M -daystart -mtime -1)"
if [ "$new" ]; then                                 # Do we have episodes.
    mount '/home/pi/Media'
    sleep 45
        while read -r vid; do
        ext="${vid##*.}"
        epi="$(strip_title <<< $(dirname "$vid" | xargs basename -a))"
        dir="${epi% [Ss][0-9]*}/Season $(tail -c 6 <<< $epi |\
        head -c 2 | sed 's/^0//')"                  # Determine directory tree.
        echo "$epi" | sed 's/^/  /' | tee -a "$rlg" "$mod" |\
        sed "s/^/$(date +%a-%d)/;s/$/  \:$(du --si "$vid" | cut -f1)/" >> "$rec"
        mkdir -p "$smb/$dir"                        # Create directory on NAS.
        cp "$vid" "$smb/$dir/$epi.$ext"             # Copy to NAS renamed.
        (( cdn+=1 ))                                # Increment LED indicator.
    done <<< "$new"
fi
# This works in conjunction with the "ted-talks.sh" script if it exists.
# The mount commands will need tailoring to your network setup. ###############
new="$(find ted -type f)"
if [ "$new" ]; then
    echo " TED session...: Downloaded "$(du --si ted | cut -f2)"B" |\
    tee -a "$rlg" "$mod"
    while read -r vid; do
        [ -e "$vid" ] && mv "$vid"\
        ted/"$(grep "${vid##*/}" scripts/ted-donelist.txt | cut -d"|" -f1-2 |\
        tr -cd [:alnum:][:blank:]).mp4"             # Make a sane filename.
        (( cdn+=1 ))
    done <<< "$new"
    ls ted | sed 's/^/  /;s/.mp4//' | cut -c1-77 | tee -a "$rlg" "$mod"
    if ! mount -l | grep $(dirname "$smb"); then
        mount '/home/pi/Media'
        sleep 45
    fi
    mv ted/* "$smb"/TED-talks
fi
# Finish up.
echo "$cdn" > 'log/flashblue.txt'                   # Flash LED $cdn times.
echo "$(tail -25 "$rec")" | tac > 'scripts/recent.txt'
if [ "$cdn" -lt "1" ]; then
    echo " This session..: $(date +%A) nothing new." | tee -a "$rlg" "$mod"
else
    echo "$(date +%T) - File(s) transfer completed." >> "$rlg"
    (
    echo -n " Script runtime: $(date -d@"$SECONDS" -u +%H:%M:%S) - "
    echo "Load average: $(awk '{print $1,$2,$3}' /proc/loadavg)"
    ) | tee -a "$rlg" "$mod"
    umount '/home/pi/Media'
fi
# exit - see trap.