#!/bin/sh
#
# taztrack.cgi: SliTaz OS tracker over the world. We dont track users
# info, no mail or IP but the localization. The goal of Sdt is
# to help show where SliTaz OS's are in the world.
#
# Sdt clients autocolect: $vers $hwtype. This script get the
# date and the geolocalization so users just have to submit there
# name/nick. And well, the idea was inspired by the Raspberry Pi
# Rastrack but the code is writen from scratch :-) DB is in the flat 
# file taztrack.txt using | as separator for easy parsing
#
# (C) SliTaz GNU/Linux 2014 - BSD License
#
. /usr/lib/slitaz/httphelper.sh
. /lib/libtaz.sh

#
# NOTES: 
#    Sdt will first be deployed for SliTaz Raspberry Pi
#    We will have a simple text/plain summary about the tracker
#

#
# API:
#    POST new distro to DB
#    GET sent DB stats
#

# Sent by the client: user="" vers="" hwtype=""
db="sdt.txt"
date="$(date +%Y%m%d)"

#
# Functions
#

# libtaz.sh will output html whatever we do... it must be fixed
separator() {
	echo "--------------------------------------------------------------------------------"
}

plain_header() {
	echo "SliTaz distro tracker"
	separator
}

plain_summary() {
	cat << EOT

DB file    : $db
Tracked    : $(wc -l $db | cut -d " " -f 1)

EOT
	IFS="|"
	cat $db | while read user distro date country
	do
		echo "$user $distro $date $country"
	done
	unset IFS
}


#
# GET actions
#

case " $(GET) " in
	*\ track\ *)
		# freegeoip.net/{format}/{ip_or_hostname}
		geoloc=""
		user=$(GET user)
		distro=$(GET track)
		#ip="$REMOTE_ADDR"
		ip=178.196.15.131
		if ! echo "$HTTP_USER_AGENT" | fgrep -q "Sdt"; then
			echo "Only Sdt clients are accepted" && exit 1
		fi
		
		echo "SliTaz Distro Tracker"
		separator
		echo "Date       : $date"
		echo "Distro     : $distro"
		echo "User name  : $user" 
		echo "IP address : $ip"
		#wget freegeoip.net/csv/${ip} -O /tmp/geoloc
		country=$(cat /tmp/geoloc | cut -d '"' -f 6 )
		echo "Country    : $country"
		# Add to DB
		echo "$user|$distro|$date|$country" >> ${db}
		;;
	*\ country\ *) 
		# Show distro's by country
		;;
	*)
		header "Content-Type: text/plain"
		plain_header
		plain_summary ;;
esac

exit 0
