#!/bin/bash
###############################################################################
# Reset download statistics for a given file in a given trac environment
# =============================================================================
# Parameters:
# $1 - Trac Environment (e.g. "/usr/local/trac/myproject")
# $2 - ID of the file to reset the statistics for (e.g. "5")
# Sample call, resetting stats for file #5 in myproject:
# ./reset_file_stats /usr/local/trac/myproject 5
###############################################################################
# $Id$

#==========================================================[ Configuration ]===
# database tool to use
DBTOOL="/usr/bin/sqlite3"
# database to use
DB="${1}/db/trac.db"

#==============================================================[ Functions ]===
#----------------------------------------------------------[ Display Usage ]---
function usage() {
  echo "------------------------------------------"
  echo "Usage:"
  echo "  ${0} <trac_env> <file_id>"
  echo
  echo "Example:"
  echo "  ${0} /usr/local/trac/myproject 5"
  echo "(Resetting stats for file #5 in myproject)"
  echo "------------------------------------------"
  echo
}

#===============================================================[ Main Job ]===
trac_env="$1"
file_id="$2"
#-----------------------------------------------------------[ Check Syntax ]---
id_test=`echo $file_id|sed 's/[^0-9]//g'`
[ ! -d "$trac_env" -o -z "$id_test" ] && {
  usage
  exit 1
}

#-------------------------------------------------------[ Reset statistics ]---
# First check if we really know that file
fid=`$DBTOOL -noheader $DB "SELECT id FROM downloader_file WHERE id=$file_id;"`
[ -z "$fid" ] && {
  echo "Sorry - we don't have a file with id #$file_id in this trac environment."
  exit 2
}
# Get the file name for verification
fname=`$DBTOOL -noheader $DB "SELECT name FROM downloader_file WHERE id=$file_id;"`
# Let the user approve (or abort)
echo "------------------------------"
echo "Resetting download statistics:"
echo "* Trac Environment: $trac_env"
echo "* File #: $file_id"
echo "* File name: $fname"
read -n 1 -p "Are you sure (y/n)? " reply
echo
[ "$reply" = "y" -o "$reply" = "Y" ] || {
  echo "Aborting."
  exit 0
}
# Reset statistics for that file
SQL="BEGIN TRANSACTION;
DELETE FROM downloader_downloaded WHERE file=$file_id;
DELETE FROM downloader_downloaded_attributes WHERE downloaded=$file_id;
COMMIT;"
$DBTOOL $DB "$SQL"
if [ $? -ne 0 ]; then
  echo "There was some error - sorry..."
  exit 3
else
  echo "Done."
fi
echo "------------------------------"
