#!/bin/bash

set -e

if type -p schedtool >/dev/null 2>&1 ; then
    SCHED="schedtool -B -n10 -e"
else
    SCHED=""
fi

if type -p shlock >/dev/null 2>&1 ; then
    LOCK=shlock
else
    LOCK=lockfile-create
fi

DEV=0
if test $(echo -n "$1" | wc -c) = 1 && test -b "/dev/sr$1"; then DEV="$1"; shift; fi
D=/dev/sr$DEV
RUN=/run/cdread/$DEV
mkdir -p $RUN

if ! $LOCK /var/lock/cdread$DEV ; then
    echo Locked. >&2
    exit 1
fi
trap 'rm -f /var/lock/cdread$DEV' EXIT

if test -d /mnt/disk/sounds ; then
        X=/mnt/disk/sounds/cd
elif test -d /smurf/sounds ; then
        X=/smurf/sounds/cd
elif test -d /d/sound ; then
        X=/d/sound/cd
elif test -d /d/Sound ; then
        X=/d/Sound/cd
elif test -d ~/sound ; then
        X=~/sound/cd
else
        echo "kein sound-Verzeichnis?" >&2
        exit 1
fi

#Filesystem         1024-blocks      Used Available Capacity Mounted on
#/dev/mapper/kiste-root  12385456   9897128   1859208      85% /

cdcd -d $D close

f0=$(tempfile -p cdrd_ -d $RUN)
f1=$(tempfile -p cdrd_ -d $RUN)
f2=$(tempfile -p cdrd_ -d $RUN)
f3=$(tempfile -p cdrd_ -d $RUN)
f4=$(tempfile -p cdrd_ -d $RUN)

trap 'rm -f $f0 $f1 $f2 $f3 $f4 /var/lock/cdread$DEV.lock' EXIT
cat <<END >$f3
import sys

def checksum(sean='602498112083'):
    s1,check=sean[:-1],sean[-1]
    sum=0
    for i in range(len(s1)):
        if (len(s1)-i)%2:
            sum+=int(s1[i])*3
        else:
            sum+=int(s1[i])
    sum = (10-sum)%10
    if int(check) != sum:
        sys.exit(1)
    sys.exit(0)

checksum(raw_input())
END

while : ; do 
    f=0
    for d in /media/*/cd /var/cache/rip/cd /var/cache/cd /var/tmp /tmp ; do
        test -d $d || continue
        df=$(df -P $d|tail -1|while read a b c d e ; do echo $d; done)
        if [ $df -gt $f ] ; then
            T=$d
            f=$df
        fi
    done
    echo $T

    cat <<END >$f0
#!/usr/bin/python3

import logging
import sys
logging.basicConfig(level=logging.DEBUG)

#import musicbrainz2.webservice as ws
import musicbrainzngs as mb
import libdiscid as ld
mb.set_useragent("smurf_cdread","0.1")

import time,sys
d=sys.argv[1]
a=open(sys.argv[2],"w")
b=open(sys.argv[3],"w")
c=open(sys.argv[4],"w")
n=0
while True:
    try:
        d = ld.read(d)
    except Exception as e:
        n += 1
        print(n,"Error:", repr(e), "\r", end="")
        sys.stdout.flush()
        time.sleep(2)
    else:
        print(" "*70, "\r", end="")
        break
print(d.id, file=a)
dly=2.0
while True:
    try:
        res = mb.get_releases_by_discid(d.id, includes=["artists"])
        break
    except mb.ResponseError as e:
        print("Error:", repr(e))
        res = None
        break

    except Exception as e:
        print("Error:", repr(e))
        time.sleep(dly)
        dly = dly * 1.6
if res:
    try:
        res = res['disc']['release-list']
    except KeyError:
        try:
            res = res['cdstub']
        except KeyError:
            print("Unknown")
        else:
            print(res['artist'].replace("/","-") + "/" + res['title'].replace("/"," - "), file=b)
    else:
        if len(res):
            res = res[0]
            part=""
            if res['medium-count'] != 1:
                part=None
                for di in res['medium-list']:
                    for dl in di['disc-list']:
                        if dl['id'] == d.id:
                            part = "%02d" % int(di['position'])
                            break
                    if part:
                        break
                else:
                    import pdb;pdb.set_trace()
                    part="01"
            ar = res['artist-credit']
            if len(ar):
                ar = ar[0]['artist']['name']
            else:
                ar = '?'
            print(ar.replace("/","-") + "/" + res['title'].replace("/"," - "), file=b)
            print(res['id'], part, file=c)
END

    python3 $f0 $D $f1 $f2 $f4

    read id <$f1
    read artist <$f2 || true
    read mbid part <$f4 || true
    if test -n "$part"; then part="$part-"; fi
    rm -f $f0 $f1
    test -n "$id"

    echo $id
    if test -z "$artist" ; then
        echo "$id *** not found ***"
    else
        echo $id === $artist
    fi

    cd $X

    mbd=$X/mb_$id
    if test -n "$mbid"; then
        mbd_="$X/../mb/$mbid"
        ff="01.opus"
        if test -n "$part" ; then
            ff="$part$ff"
        fi
        if test -f "$mbd_/$ff" ; then
            echo "$id : : $mbid :: ${part}known"
            eject $D
            cdcd -d $D open
            continue
        fi
        echo "$id ::: $part$mbid"
        mbd="$mbd_"
    elif test -d "$mbd" ; then
        echo $id . . ${part}known
        eject $D
        cdcd -d $D open
        continue
    fi

    mkdir -p $mbd $RUN/$id
    cd $mbd
    echo mbid $id > .id
    touch $RUN/$id/WORKING
    (
        cd $RUN/$id
        cur=01
        while sleep 1 ; do 
            f="track$cur.cdda.wav"
            if test ! -f track$cur.cdda.wav ; then
                if test ! -f WORKING ; then break; fi
                continue
            fi

            nxt=$(printf "%02d" $(expr $cur + 1) )
            if test ! -f track$nxt.cdda.wav ; then
                if test -f WORKING ; then
                    continue
                fi
            fi

            df="$mbd/$part$cur.opus"
            #$SCHED oggenc -Q -q5 "$@" -o "$df" $f
            $SCHED opusenc --quiet --bitrate=140 "$@" "$f" "$df"
            rm $f
        done
        echo $id . . done
        cd /
        rm -r $RUN/$id
    ) &

    if test -z "$artist" ; then
        echo -n "Artist: " ; read a ; test -z "$a" || echo artist $a >> .id
        echo -n "Title: " ; read t ; test -z "$t" || echo title $t >> .id
        while : ; do
            echo -n "Barcode: " ; read b ; test -n "$b" || break
            if echo $b | python $f3 ; then
                echo barcode $b >> .id
                break
            fi
            echo "*** Wrong barcode checksum ***"
        done
    fi
    cd $RUN/$id
    echo $id ... reading
    if ! cdparanoia -q -z3 -d $D -B ; then
        cd /
        rm -r $T/$id
        cd $mbd
        cur=01
        while test -f $part$cur.opus ; do
            rm $part$cur.opus
            cur=$(printf "%02d" $(expr $cur + 1) )
        done
        echo "$id ??? no cd read"
        cd $X
        continue
    fi
    rm $T/$id/WORKING

    # nice -15 lame --nogapout . --quiet --r3mix "$@" --nogap --nogaptags *.wav
    eject $D
    cdcd -d $D open

done
