#! /bin/bash

# ----------------------------------------------------------------------
# Description: save audacious play history to a sqlite3 database
# Author:  Artem S. Tashkinov
# Created at: Sat Dec 29 12:34:46 UTC 2018
# Computer: localhost.localdomain
# System: Linux 4.19.10-300.fc29.x86_64 on x86_64
# ----------------------------------------------------------------------

DB=$HOME/.local/share/audacious/play_history.db

die()
{
    xmessage -timeout 3 "$1" 2>/dev/null &
    exit 1
}

escape()
{
    # I just cannot understand what needs to be escaped and how: sqlite is not friendly to shell scripting
    # This is as safe as possible without maiming your playlist entries too much: you need to say goodbye to ' " ( ) ; characters
    audtool current-song-tuple-data "$1" | tr "\"()';" "_"
}

test -f "$DB" || touch "$DB"
test -f "$DB" || die "Can't create $DB!"

sqlite3 "$DB"  <<EOF
CREATE TABLE IF NOT EXISTS history (
 id INTEGER PRIMARY KEY,
 unixtime INTEGER NOT NULL,
 artist TEXT,
 title TEXT,
 album text,
 year text
);
EOF

test "$?" -eq 0 || die "sqlite create table failed!"

now=`date +%s`
artist=`escape artist`
title=`escape title`
album=`escape album`
year=`escape year`

echo "INSERT INTO history (unixtime, artist, title, album, year) VALUES (\"$now\", \"$artist\", \"$title\", \"$album\", \"$year\");" | sqlite3 "$DB"
