#!/bin/sh
#
# SDT - SliTaz Distro Tracker Cmdline client
#
# (C) SliTaz GNU/Linux 2017 - BSD License
#
. /lib/libtaz.sh

version="0.1"
url="http://scn.slitaz.org/"
date="$(date +%Y%m%d)"
mark="$HOME/.cache/slitaz/sdt.log"

get_geoloc() {
	# freegeoip.net/<format>/[<ip_or_hostname>]
	# Example: wget freegeoip.net/csv/$ip -O /tmp/geoloc
	wget -q http://freegeoip.net/csv/ -O- | cut -d, -f3
}

get_mode() {
	if grep -q "root=/dev/null" /proc/cmdline; then
		echo "live"
	else
		echo "install"
	fi
}

case "$1" in
	get-stats)
		# Get some info from the DB
		title "SDT Stats"
		if wget -q -T 5 --spider $url; then
			echo "Tracker is online..."
			wget -q "$url?sdt=raw" -O-
		else
			echo "Tracker is unreachable..."
		fi
		footer
		;;
	send)
		# Send stats to online DB
		if [ -f "$mark" ]; then
			echo "It looks like you already sent this distro to the DB"
			exit 0
		fi
		user="$2"
		[ -n "$user" ] || user="anonymous"
		country=$(get_geoloc)
		release=$(cat /etc/slitaz-release)
		kernel=$(uname -r)
		mode=$(get_mode)
		cat <<EOT

$(boldify "Information that will be sent to the SliTaz Distro Tracker")
$(separator)
User         : $user
Country      : $country
Release      : SliTaz $release
Kernel       : $kernel
Running      : $mode
EOT
		footer
		echo "Send this data to SliTaz Distro Tracker?"
		echo -n "Press 'c' then ENTER to continue or any other key to quit: "
		read answer; newline
		[ "$answer" = 'c' ] || exit 0

		echo "Sending data to $url"; newline
		wget -q --user-agent "SliTaz/SDT" \
"$url?sdt=add&user=$user&country=$country&release=$release&kernel=$kernel&mode=$mode" \
			-O-
		mkdir -p $(dirname $mark)
		echo "sent" > $mark
		;;
	*)
		newline
		echo "$(boldify 'Usage:') $(basename $0) [get-stats|send] [username]"
		newline
		;;
esac
exit 0
