#!/usr/bin/sh
#
# $Id: mpdhist.in,v 1.5 2024-03-11 16:47:12+05:30 Cprogrammer Exp mbhangui $
#

usage()
{
cat 1>&2 <<EOF
Usage: mpdhist [OPTION]

Known values for OPTION are:

-l limit
--limit=limit
  Finds song with uri matching path

-r
--reverse
  Reverse the order with song heard first
  at the top

-h
--help
  display this help and exit
EOF
exit $1
}

get_mpd_conf_value()
{
  grep "^$1" /etc/mpd.conf|awk '{print $2}' | \
  sed -e 's{"{{g'
}

process_cmdline()
{
OPTS=$(getopt -o l:hr --long limit:,help,reverse -- "$@")
if [ $? -ne 0 ] ; then
  usage 1
fi
#echo "OPTS=$OPTS"
#echo "args=$@"
eval set -- "$OPTS"
while true; do
  case "$1" in
  -l|--limit)
    limit=$2
    shift 2
  ;;
  -r|--reverse)
    do_rev=1
	shift
  ;;
  -h|--help)
    usage 0
  ;;
  --)
    shift
    break
  ;;
  *)
    echo "invalid option [$1]" 1>&2
    usage 1;
    break
  ;;
  esac
done
}

limit=24
do_rev=0
process_cmdline "$@"

music_dir=`get_mpd_conf_value music_directory`
if [ $? -ne 0 ] ; then
  echo "could not get music directory from mpd.conf" 1>&2
  exit 1
fi
sticker_file=`get_mpd_conf_value sticker_file`
if [ $? -ne 0 ] ; then
  echo "could not get sticker database from mpd.conf" 1>&2
  exit 1
fi
stats_dir=$(dirname $sticker_file)
stats_file=$stats_dir/stats.db
stmt=""
stmt="$stmt select id, title, artist, album, play_count, rating, "
stmt="$stmt strftime('%d-%m-%Y %H:%M:%S', datetime(last_played, 'unixepoch', 'localtime'))  "
if [ $do_rev -eq 0 ] ; then
  stmt="$stmt from song where last_played is NOT NULL and play_count > 0 order by last_played DESC LIMIT $limit"
else
  stmt="$stmt from song where last_played is NOT NULL and play_count > 0 order by last_played ASC LIMIT $limit"
fi

sqlite3 -header -batch -column $stats_file "$stmt" | \
  sed \
    -e 's/[ \t]\+$//' \
    -e 's{strftime.*${Last Played{' \
    -e 's{ -*${ ==================={'

#
# $Log: mpdhist.in,v $
# Revision 1.5  2024-03-11 16:47:12+05:30  Cprogrammer
# removed rompr
#
# Revision 1.4  2022-09-26 21:15:59+05:30  Cprogrammer
# removed debug statement
#
# Revision 1.3  2022-09-26 21:12:59+05:30  Cprogrammer
# added -r option to show earliest played song first
#
# Revision 1.2  2022-09-26 20:18:34+05:30  Cprogrammer
# pass -header option to sqlite3
#
# Revision 1.1  2022-09-26 19:11:08+05:30  Cprogrammer
# Initial revision
#
#
