#!/bin/sh
#
#    50-news - print the live news from the Ubuntu wire
#    Copyright (C) 2016 Canonical Ltd.
#
#    Authors: Dustin Kirkland <kirkland@canonical.com>
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License along
#    with this program; if not, write to the Free Software Foundation, Inc.,
#    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

# Source our configuration
[ -r /etc/default/motd-news ] && . /etc/default/motd-news
ENABLED=1 || exit 0
[ -n "$SERVER" ] || SERVER="https://motd.ubuntu.com"
[ -n "$WAIT" ] || WAIT=2
# Generate our temp files, clean up when done
NEWS=$(mktemp)
ERR="$NEWS.err"
trap "rm -f $NEWS $ERR" HUP INT QUIT ILL TRAP KILL BUS TERM

# Construct a user agent, with debug information, similar to Firefox/Chrome
curl_ver="$(dpkg -l curl | awk '$1 == "ii" { print($3); exit(0); }')"
. /etc/lsb-release
lsb=$(echo "$DISTRIB_DESCRIPTION" | sed -e "s/ /\//g")
platform="$(uname -o)/$(uname -r)/$(uname -m)"
cpu="$(grep -m1 "^model name" /proc/cpuinfo | sed -e "s/.*: //" -e "s:\s\+:/:g")"
read up idle < /proc/uptime
uptime="uptime/$up/$idle"
USER_AGENT="curl/$curl_ver $lsb $platform $cpu $uptime"

for s in $SERVER; do
	# Ensure https:// protocol, for security reasons
	case $s in
		https://*)
			true
		;;
		*)
			continue
		;;
	esac
	# Fetch and print the news motd
	if curl --connect-timeout "$WAIT" --max-time "$WAIT" -A "$USER_AGENT" -o- "$s" >"$NEWS" 2>"$ERR"; then
		echo
		# At most, 10 lines of text, remove control characters, print at most 80 characters per line
		cat "$NEWS" | head -n 10 | tr -d '\000-\011\013\014\016-\037' | cut -c -80
	fi
done
rm -f "$NEWS" "$NEWS.err"
exit 0
