#!/bin/sh
################################################################################
# disc_id.sh -- pyllyukko at maimed dot org -- no guarantees                   #
#                                                                              #
# this script doesn't have much error checking... so beware.                   #
#                                                                              #
# modified:	2010 Aug 17
#                                                                              #
# TODO:                                                                        #
#   15.11.2009: implement cddbp support                                        #
#                                                                              #
################################################################################
# Query database for matching entries:
# ------------------------------------
# Client command:
# -> cddb query discid ntrks off1 off2 ... nsecs
#
#     discid:
# 	CD disc ID number.  Example: f50a3b13
#     ntrks:
# 	Total number of tracks on CD.
#     off1, off2, ...:
# 	Frame offset of the starting location of each track.
#     nsecs:
# 	Total playing length of CD in seconds.
################################################################################
alias cdparanoia=/usr/bin/cdparanoia
################################################################################
function disc_id() {
  cdparanoia -Q 2>&1 | awk '
  function cddb_sum(x) {
    ret = 0
    while(x>0) {
      ret += (x % 10)
      x = sprintf("%d", x/10)
    }
    return ret
  } {
    # tracks
    if($1 ~ /^[0-9]/) {
      match($5, /^\[([0-9]+):([0-9]+)\.[0-9]+]$/, arr)
      minutes = arr[1]
      # 2-second offset from the start of disc data
      seconds = arr[2]+2
      n = n + cddb_sum((minutes*60)+seconds)
      tracks++
    } else if($1 ~ /^TOTAL$/) {
      match($3, /^\[([0-9]+):([0-9]+)\.[0-9]+]$/, arr)
      total["minutes"] = arr[1]
      total["seconds"] = arr[2]
    }
  } END {
    t = (total["minutes"]*60)+total["seconds"]
    disc_id = or(or(lshift((n%0xff), 24), lshift(t, 8)), tracks)
    printf "%08x", disc_id
  }'
  return $[ ${PIPESTATUS[0]} | ${PIPESTATUS[1]} ]
} # disc_id()
################################################################################
DISC_ID=`disc_id`
echo "disc id: ${DISC_ID}"
exit 0

