Replace struct table_info by struct afs_table.
[paraslash.git] / aft.c
diff --git a/aft.c b/aft.c
index ac7d9a1a34c69412242bef6631841238f07d8aea..c63ab47106866dd5caa9e99062377c742b999a68 100644 (file)
--- a/aft.c
+++ b/aft.c
+/*
+ * Copyright (C) 2007 Andre Noll <maan@systemlinux.org>
+ *
+ * Licensed under the GPL v2. For licencing details see COPYING.
+ */
+
+/** \file aft.c Audio file table functions. */
+
 #include "para.h"
 #include "error.h"
+#include "string.h"
 #include <sys/mman.h>
 #include <fnmatch.h>
 #include "afh.h"
 #include "afs.h"
 #include "net.h"
-#include "string.h"
 #include "vss.h"
 
-#define AFS_AUDIO_FILE_DIR "/home/mp3"
-
 static struct osl_table *audio_file_table;
 
+/** The different sorting methods of the ls command. */
+enum ls_sorting_method {
+       /** -sp (default) */
+       LS_SORT_BY_PATH,
+       /** -ss */
+       LS_SORT_BY_SCORE,
+       /** -sl */
+       LS_SORT_BY_LAST_PLAYED,
+       /** -sn */
+       LS_SORT_BY_NUM_PLAYED,
+       /** -sf */
+       LS_SORT_BY_FREQUENCY,
+       /** -sc */
+       LS_SORT_BY_CHANNELS,
+       /** -si */
+       LS_SORT_BY_IMAGE_ID,
+       /** -sy */
+       LS_SORT_BY_LYRICS_ID,
+       /** -sb */
+       LS_SORT_BY_BITRATE,
+       /** -sd */
+       LS_SORT_BY_DURATION,
+       /** -sa */
+       LS_SORT_BY_AUDIO_FORMAT,
+       /** -sh */
+       LS_SORT_BY_HASH,
+};
+
+/** The different listing modes of the ls command. */
+enum ls_listing_mode {
+       /** Default listing mode. */
+       LS_MODE_SHORT,
+       /** -l or -ll */
+       LS_MODE_LONG,
+       /** -lv */
+       LS_MODE_VERBOSE,
+       /** -lm */
+       LS_MODE_MBOX
+};
+
+/** The flags accepted by the ls command. */
+enum ls_flags {
+       /** -p */
+       LS_FLAG_FULL_PATH = 1,
+       /** -a */
+       LS_FLAG_ADMISSIBLE_ONLY = 2,
+       /** -r */
+       LS_FLAG_REVERSE = 4,
+};
+
+/**
+ * The size of the individual output fields of the ls command.
+ *
+ * These depend on the actual content being listed. If, for instance only files
+ * with duration less than an hour are being listed, then the duration with is
+ * made smaller because then the duration is listed as mm:ss rather than
+ * hh:mm:ss.
+ */
+struct ls_widths {
+       /** size of the score field. */
+       unsigned short score_width;
+       /** size of the image id field. */
+       unsigned short image_id_width;
+       /** size of the lyrics id field. */
+       unsigned short lyrics_id_width;
+       /** size of the bitrate field. */
+       unsigned short bitrate_width;
+       /** size of the frequency field. */
+       unsigned short frequency_width;
+       /** size of the duration field. */
+       unsigned short duration_width;
+       /** size of the num played field. */
+       unsigned short num_played_width;
+};
+
+/** Data passed to the different compare functions (called by qsort()). */
+struct ls_data {
+       /** Usual audio format handler information. */
+       struct audio_format_info afhi;
+       /** Audio file selector information. */
+       struct afs_info afsi;
+       /** The full path of the audio file. */
+       char *path;
+       /** The score value (if -a was given). */
+       long score;
+       /** The sha1 hash of audio file. */
+       HASH_TYPE *hash;
+};
+
+struct ls_options {
+       unsigned flags;
+       enum ls_sorting_method sorting;
+       enum ls_listing_mode mode;
+       char **patterns;
+       int num_patterns;
+       struct ls_widths widths;
+       uint32_t array_size;
+       uint32_t num_matching_paths;
+       struct ls_data *data;
+       struct ls_data **data_ptr;
+};
+
 /**
  * Describes the layout of the mmapped-afs info struct.
  *
@@ -69,7 +177,7 @@ int load_afsi(struct afs_info *afsi, struct osl_object *obj)
 {
        char *buf = obj->data;
        if (obj->size < AFSI_SIZE)
-               return -E_BAD_AFS;
+               return -E_BAD_AFSI;
        afsi->last_played = read_u64(buf + AFSI_LAST_PLAYED_OFFSET);
        afsi->attributes = read_u64(buf + AFSI_ATTRIBUTES_OFFSET);
        afsi->num_played = read_u32(buf + AFSI_NUM_PLAYED_OFFSET);
@@ -133,60 +241,7 @@ static struct osl_table_description audio_file_table_desc = {
        .column_descriptions = aft_cols
 };
 
-static char *prefix_path(const char *prefix, int len, const char *path)
-{
-       int speclen;
-       char *n;
-
-       for (;;) {
-               char c;
-               if (*path != '.')
-                       break;
-               c = path[1];
-               /* "." */
-               if (!c) {
-                       path++;
-                       break;
-               }
-               /* "./" */
-               if (c == '/') {
-                       path += 2;
-                       continue;
-               }
-               if (c != '.')
-                       break;
-               c = path[2];
-               if (!c)
-                       path += 2;
-               else if (c == '/')
-                       path += 3;
-               else
-                       break;
-               /* ".." and "../" */
-               /* Remove last component of the prefix */
-               do {
-                       if (!len)
-                               return NULL;
-                       len--;
-               } while (len && prefix[len-1] != '/');
-               continue;
-       }
-       if (!len)
-               return para_strdup(path);
-       speclen = strlen(path);
-       n = para_malloc(speclen + len + 1);
-       memcpy(n, prefix, len);
-       memcpy(n + len, path, speclen+1);
-       return n;
-}
-
-/*
- * We fundamentally don't like some paths: we don't want
- * dot or dot-dot anywhere.
- *
- * Also, we don't want double slashes or slashes at the
- * end that can make pathnames ambiguous.
- */
+/* We don't want * dot or dot-dot anywhere. */
 static int verify_dotfile(const char *rest)
 {
        /*
@@ -194,57 +249,68 @@ static int verify_dotfile(const char *rest)
         * now test the rest.
         */
        switch (*rest) {
-       /* "." is not allowed */
-       case '\0': case '/':
-               return 1;
-
-       case '.':
+       case '\0': case '/': /* /foo/. and /foo/./bar are not ok */
+               return -1;
+       case '.': /* path start with /foo/.. */
                if (rest[1] == '\0' || rest[1] == '/')
-                       return -1;
+                       return -1; /* /foo/.. or /foo/../bar are not ok */
+               /* /foo/..bar is ok */
        }
        return 1;
 }
 
+/*
+ * We fundamentally don't like some paths: We don't want double slashes or
+ * slashes at the end that can make pathnames ambiguous.
+ */
 static int verify_path(const char *orig_path, char **resolved_path)
 {
        char c;
-       const char prefix[] = AFS_AUDIO_FILE_DIR "/";
-       const char *path = orig_path;
-       const size_t prefix_len = strlen(prefix);
+       size_t len;
+       char *path;
 
+       if (*orig_path != '/') /* we only accept absolute paths */
+               return -E_BAD_PATH;
+       len = strlen(orig_path);
+       *resolved_path = para_strdup(orig_path);
+       path = *resolved_path;
+       while (len > 1 && path[--len] == '/')
+               path[len] = '\0'; /* remove slash at the end */
        c = *path++;
-       if (!c)
-               goto bad_path;
        while (c) {
                if (c == '/') {
                        c = *path++;
                        switch (c) {
-                       default:
-                               continue;
                        case '/': /* double slash */
                                goto bad_path;
                        case '.':
                                if (verify_dotfile(path) < 0)
                                        goto bad_path;
+                       default:
+                               continue;
                        }
                }
                c = *path++;
        }
-       if (*orig_path != '/')
-               *resolved_path = prefix_path(prefix, prefix_len, orig_path);
-       else
-               *resolved_path = para_strdup(orig_path);
        return 1;
 bad_path:
+       free(*resolved_path);
        return -E_BAD_PATH;
 }
 
+/** The on-disk layout of a afhi struct. */
 enum afhi_offsets {
+       /** Where the number of seconds is stored. */
        AFHI_SECONDS_TOTAL_OFFSET = 0,
+       /** Position of the bitrate. */
        AFHI_BITRATE_OFFSET = 4,
+       /** Position of the frequency. */
        AFHI_FREQUENCY_OFFSET = 8,
+       /** Number of channels is stored here. */
        AFHI_CHANNELS_OFFSET = 12,
+       /** The tag info position. */
        AFHI_INFO_STRING_OFFSET = 13,
+       /** Minimal on-disk size of a valid afhi struct. */
        MIN_AFHI_SIZE = 14
 };
 
@@ -347,11 +413,10 @@ static int load_chunk_info(struct osl_object *obj, struct audio_format_info *afh
  *
  * \return The return value of the underlying call to osl_get_row().
  */
-int aft_get_row_of_path(char *path, struct osl_row **row)
+int aft_get_row_of_path(const char *path, struct osl_row **row)
 {
-       struct osl_object obj = {.data = path, .size = strlen(path) + 1};
+       struct osl_object obj = {.data = (char *)path, .size = strlen(path) + 1};
 
-       PARA_NOTICE_LOG("audio_file_table: %p\n", audio_file_table);
        return osl_get_row(audio_file_table, AFTCOL_PATH, &obj, row);
 }
 
@@ -377,7 +442,7 @@ int aft_get_row_of_hash(HASH_TYPE *hash, struct osl_row **row)
  *
  * \return The return value of the underlying call to osl_get_object().
  */
-int get_afsi_object_of_row(const void *row, struct osl_object *obj)
+int get_afsi_object_of_row(const struct osl_row *row, struct osl_object *obj)
 {
        return osl_get_object(audio_file_table, row, AFTCOL_AFSI, obj);
 }
@@ -391,7 +456,7 @@ int get_afsi_object_of_row(const void *row, struct osl_object *obj)
  *
  * \return Positive on success, negative on errors.
  */
-int get_afsi_object_of_path(char *path, struct osl_object *obj)
+int get_afsi_object_of_path(const char *path, struct osl_object *obj)
 {
        struct osl_row *row;
        int ret = aft_get_row_of_path(path, &row);
@@ -417,6 +482,23 @@ int get_afsi_of_row(const struct osl_row *row, struct afs_info *afsi)
        return load_afsi(afsi, &obj);
 }
 
+/**
+ * Get the audio file selector info, given the path of an audio table.
+ *
+ * \param path The full path of the audio file.
+ * \param afsi Result pointer.
+ *
+ * \return Positive on success, negative on errors.
+ */
+int get_afsi_of_path(const char *path, struct afs_info *afsi)
+{
+       struct osl_object obj;
+       int ret = get_afsi_object_of_path(path, &obj);
+       if (ret < 0)
+               return ret;
+       return load_afsi(afsi, &obj);
+}
+
 /**
  * Get the path of an audio file, given a row of the audio file table.
  *
@@ -446,7 +528,7 @@ int get_audio_file_path_of_row(const struct osl_row *row, char **path)
  *
  * \sa get_hash_of_row().
  */
-int get_hash_object_of_aft_row(const void *row, struct osl_object *obj)
+static int get_hash_object_of_aft_row(const struct osl_row *row, struct osl_object *obj)
 {
        return osl_get_object(audio_file_table, row, AFTCOL_HASH, obj);
 }
@@ -462,7 +544,7 @@ int get_hash_object_of_aft_row(const void *row, struct osl_object *obj)
  * \return The return value of the underlying call to
  * get_hash_object_of_aft_row().
  */
-static int get_hash_of_row(const void *row, HASH_TYPE **hash)
+static int get_hash_of_row(const struct osl_row *row, HASH_TYPE **hash)
 {
        struct osl_object obj;
        int ret = get_hash_object_of_aft_row(row, &obj);
@@ -483,7 +565,7 @@ static int get_hash_of_row(const void *row, HASH_TYPE **hash)
  *
  * \sa get_chunk_table_of_row().
  */
-int get_afhi_of_row(const void *row, struct audio_format_info *afhi)
+int get_afhi_of_row(const struct osl_row *row, struct audio_format_info *afhi)
 {
        struct osl_object obj;
        int ret = osl_get_object(audio_file_table, row, AFTCOL_AFHI,
@@ -504,7 +586,7 @@ int get_afhi_of_row(const void *row, struct audio_format_info *afhi)
  *
  * \sa get_afhi_of_row().
  */
-int get_chunk_table_of_row(const void *row, struct audio_format_info *afhi)
+static int get_chunk_table_of_row(const struct osl_row *row, struct audio_format_info *afhi)
 {
        struct osl_object obj;
        int ret = osl_open_disk_object(audio_file_table, row, AFTCOL_CHUNKS,
@@ -573,15 +655,19 @@ err:
        return ret;
 }
 
-time_t now;
-
-static int get_local_time(uint64_t *seconds, char *buf, size_t size)
+static int get_local_time(uint64_t *seconds, char *buf, size_t size,
+       time_t current_time, enum ls_listing_mode lm)
 {
        struct tm t;
 
        if (!localtime_r((time_t *)seconds, &t))
                return -E_LOCALTIME;
-       if (*seconds + 6 * 30 * 24 * 3600 > now) {
+       if (lm == LS_MODE_MBOX) {
+               if (!strftime(buf, size, "%c", &t))
+                       return -E_STRFTIME;
+               return 1;
+       }
+       if (*seconds + 6 * 30 * 24 * 3600 > current_time) {
                if (!strftime(buf, size, "%b %e %k:%M", &t))
                        return -E_STRFTIME;
                return 1;
@@ -591,6 +677,7 @@ static int get_local_time(uint64_t *seconds, char *buf, size_t size)
        return 1;
 }
 
+/** Compute the number of (decimal) digits of a number. */
 #define GET_NUM_DIGITS(x, num) { \
        typeof((x)) _tmp = PARA_ABS(x); \
        *num = 1; \
@@ -601,25 +688,27 @@ static int get_local_time(uint64_t *seconds, char *buf, size_t size)
                } \
        }
 
-static short unsigned get_duration(int seconds_total, char *buf, short unsigned max_width)
+static short unsigned get_duration_width(int seconds)
 {
        short unsigned width;
-       int s = seconds_total;
-       unsigned hours = s / 3600, mins = (s % 3600) / 60, secs = s % 60;
-
-       if (s < 3600) { /* less than one hour => m:ss or mm:ss */
-               GET_NUM_DIGITS(mins, &width); /* 1 or 2 */
-               width += 3; /* 4 or 5 */
-               if (buf)
-                       sprintf(buf, "%*u:%02u", max_width - width + 1, mins, secs);
-               return width;
-       }
+       unsigned hours = seconds / 3600, mins = (seconds % 3600) / 60;
+
+       if (!hours) /* less than one hour => m:ss or mm:ss => 4 or 5 digits */
+               return 4 + (mins > 9);
        /* more than one hour => h:mm:ss, hh:mm:ss, hhh:mm:ss, ... */
        GET_NUM_DIGITS(hours, &width);
-       width += 6;
-       if (buf)
-               sprintf(buf, "%*u:%02u:%02u", max_width - width + 1, hours, mins, secs);
-       return width;
+       return width + 6;
+}
+
+static void get_duration_buf(int seconds, char *buf, short unsigned max_width)
+{
+       unsigned hours = seconds / 3600, mins = (seconds % 3600) / 60;
+
+       if (!hours) /* m:ss or mm:ss */
+               sprintf(buf, "%*u:%02u", max_width - 3, mins, seconds % 60);
+       else /* more than one hour => h:mm:ss, hh:mm:ss, hhh:mm:ss, ... */
+               sprintf(buf, "%*u:%02u:%02u", max_width - 6, hours, mins,
+                       seconds % 60);
 }
 
 static char *make_attribute_line(const char *att_bitmap, struct afs_info *afsi)
@@ -637,6 +726,7 @@ static char *make_attribute_line(const char *att_bitmap, struct afs_info *afsi)
 static char *make_lyrics_line(struct afs_info *afsi)
 {
        char *lyrics_name;
+
        lyr_get_name_by_id(afsi->lyrics_id, &lyrics_name);
        if (!lyrics_name)
                return make_message("%u", afsi->lyrics_id);
@@ -653,7 +743,7 @@ static char *make_image_line(struct afs_info *afsi)
 }
 
 static int print_list_item(struct ls_data *d, struct ls_options *opts,
-       struct para_buffer *b)
+       struct para_buffer *b, time_t current_time)
 {
        int ret;
        char att_buf[65];
@@ -664,6 +754,8 @@ static int print_list_item(struct ls_data *d, struct ls_options *opts,
        struct audio_format_info *afhi = &d->afhi;
        struct ls_widths *w = &opts->widths;
        int have_score = opts->flags & LS_FLAG_ADMISSIBLE_ONLY;
+       char asc_hash[2 * HASH_SIZE + 1];
+       char *att_line, *lyrics_line, *image_line;
 
        if (opts->mode == LS_MODE_SHORT) {
                para_printf(b, "%s\n", d->path);
@@ -671,10 +763,10 @@ static int print_list_item(struct ls_data *d, struct ls_options *opts,
        }
        get_attribute_bitmap(&afsi->attributes, att_buf);
        ret = get_local_time(&afsi->last_played, last_played_time,
-               sizeof(last_played_time));
+               sizeof(last_played_time), current_time, opts->mode);
        if (ret < 0)
                return ret;
-       get_duration(afhi->seconds_total, duration_buf, w->duration_width);
+       get_duration_buf(afhi->seconds_total, duration_buf, w->duration_width);
        if (have_score) {
                if (opts->mode == LS_MODE_LONG)
                        sprintf(score_buf, "%*li ", w->score_width, d->score);
@@ -682,6 +774,7 @@ static int print_list_item(struct ls_data *d, struct ls_options *opts,
                        sprintf(score_buf, "%li ", d->score);
        }
 
+       PARA_NOTICE_LOG("id: %s, %d\n", d->path, afsi->audio_format_id);
        if (opts->mode == LS_MODE_LONG) {
                para_printf(b,
                        "%s"    /* score */
@@ -711,14 +804,12 @@ static int print_list_item(struct ls_data *d, struct ls_options *opts,
                );
                return 1;
        }
+       hash_to_asc(d->hash, asc_hash);
+       att_line = make_attribute_line(att_buf, afsi);
+       lyrics_line = make_lyrics_line(afsi);
+       image_line = make_image_line(afsi);
        if (opts->mode == LS_MODE_VERBOSE) {
-               char asc_hash[2 * HASH_SIZE + 1];
-               char *att_line, *lyrics_line, *image_line;
 
-               hash_to_asc(d->hash, asc_hash);
-               att_line = make_attribute_line(att_buf, afsi);
-               lyrics_line = make_lyrics_line(afsi);
-               image_line = make_image_line(afsi);
                para_printf(b,
                        "%s: %s\n" /* path */
                        "%s%s%s" /* score */
@@ -732,7 +823,8 @@ static int print_list_item(struct ls_data *d, struct ls_options *opts,
                        "channels: %d\n"
                        "duration: %s\n"
                        "num_played: %d\n"
-                       "last_played: %s\n\n",
+                       "last_played: %s\n"
+                       "tag info: %s\n",
                        (opts->flags & LS_FLAG_FULL_PATH)?
                                "path" : "file", d->path,
                        have_score? "score: " : "", score_buf,
@@ -747,13 +839,53 @@ static int print_list_item(struct ls_data *d, struct ls_options *opts,
                        afhi->channels,
                        duration_buf,
                        afsi->num_played,
-                       last_played_time
+                       last_played_time,
+                       afhi->info_string
                );
-               free(att_line);
-               free(lyrics_line);
-               free(image_line);
-               return 1;
+       } else { /* mbox mode */
+               struct osl_object lyrics_def;
+               lyr_get_def_by_id(afsi->lyrics_id, &lyrics_def);
+               para_printf(b,
+                       "From foo@localhost %s\n"
+                       "Received: from\nTo: bar\nFrom: a\n"
+                       "Subject: %s\n\n" /* path */
+                       "%s%s%s" /* score */
+                       "attributes: %s\n"
+                       "hash: %s\n"
+                       "image_id: %s\n"
+                       "lyrics_id: %s\n"
+                       "bitrate: %dkbit/s\n"
+                       "format: %s\n"
+                       "frequency: %dHz\n"
+                       "channels: %d\n"
+                       "duration: %s\n"
+                       "num_played: %d\n"
+                       "tag info: %s\n"
+                       "%s%s\n",
+                       last_played_time,
+                       d->path,
+                       have_score? "score: " : "", score_buf,
+                               have_score? "\n" : "",
+                       att_line,
+                       asc_hash,
+                       image_line,
+                       lyrics_line,
+                       afhi->bitrate,
+                       audio_format_name(afsi->audio_format_id),
+                       afhi->frequency,
+                       afhi->channels,
+                       duration_buf,
+                       afsi->num_played,
+                       afhi->info_string,
+                       lyrics_def.data? "Lyrics:\n~~~~~~~\n" : "",
+                       lyrics_def.data? (char *)lyrics_def.data : ""
+               );
+               if (lyrics_def.data)
+                       osl_close_disk_object(lyrics_def.data);
        }
+       free(att_line);
+       free(lyrics_line);
+       free(image_line);
        return 1;
 }
 
@@ -826,7 +958,7 @@ static int ls_path_compare(const void *a, const void *b)
 static int sort_matching_paths(struct ls_options *options)
 {
        size_t nmemb = options->num_matching_paths;
-       size_t size = sizeof(uint32_t);
+       size_t size = sizeof(*options->data_ptr);
        int (*compar)(const void *, const void *);
        int i;
 
@@ -903,7 +1035,7 @@ static int prepare_ls_row(struct osl_row *row, void *ls_opts)
        }
        if (options->num_patterns) {
                for (i = 0; i < options->num_patterns; i++) {
-                       ret = fnmatch(options->patterns[i], path, FNM_PATHNAME);
+                       ret = fnmatch(options->patterns[i], path, 0);
                        if (!ret)
                                break;
                        if (ret == FNM_NOMATCH)
@@ -942,8 +1074,8 @@ static int prepare_ls_row(struct osl_row *row, void *ls_opts)
        w->frequency_width = PARA_MAX(w->frequency_width, num_digits);
        GET_NUM_DIGITS(d->afsi.num_played, &num_digits);
        w->num_played_width = PARA_MAX(w->num_played_width, num_digits);
-       /* just get the number of chars to print this amount of time */
-       tmp = get_duration(d->afhi.seconds_total, NULL, 0);
+       /* get the number of chars to print this amount of time */
+       tmp = get_duration_width(d->afhi.seconds_total);
        w->duration_width = PARA_MAX(w->duration_width, tmp);
        if (options->flags & LS_FLAG_ADMISSIBLE_ONLY) {
                GET_NUM_DIGITS(score, &num_digits);
@@ -961,6 +1093,8 @@ static int com_ls_callback(const struct osl_object *query,
        char *p, *pattern_start = (char *)query->data + sizeof(*opts);
        struct para_buffer b = {.buf = NULL, .size = 0};
        int i = 0, ret;
+       time_t current_time;
+
 
        PARA_NOTICE_LOG("%d patterns\n", opts->num_patterns);
        if (opts->num_patterns) {
@@ -987,15 +1121,16 @@ static int com_ls_callback(const struct osl_object *query,
        ret = sort_matching_paths(opts);
        if (ret < 0)
                goto out;
+       time(&current_time);
        if (opts->flags & LS_FLAG_REVERSE)
                for (i = opts->num_matching_paths - 1; i >= 0; i--) {
-                       ret = print_list_item(opts->data_ptr[i], opts, &b);
+                       ret = print_list_item(opts->data_ptr[i], opts, &b, current_time);
                        if (ret < 0)
                                break;
                }
        else
                for (i = 0; i < opts->num_matching_paths; i++) {
-                       ret = print_list_item(opts->data_ptr[i], opts, &b);
+                       ret = print_list_item(opts->data_ptr[i], opts, &b, current_time);
                        if (ret < 0)
                                break;
                }
@@ -1011,7 +1146,7 @@ out:
 }
 
 /*
- * TODO: flags -h (sort by hash)
+ * TODO: flags -h (sort by hash) -lm (list in mbox format)
  *
  * long list: list hash, attributes as (xx--x-x-), file size, lastplayed
  * full list: list everything, including afsi, afhi, atts as clear text
@@ -1115,7 +1250,6 @@ int com_afs_ls(int fd, int argc, char * const * const argv)
                }
                return -E_AFT_SYNTAX;
        }
-       time(&now);
        opts.flags = flags;
        opts.sorting = sort;
        opts.mode = mode;
@@ -1237,15 +1371,20 @@ afhi <=> force or no HS
 
 */
 
-
-#define ADD_FLAG_LAZY 1
-#define ADD_FLAG_FORCE 2
-#define ADD_FLAG_VERBOSE 4
-
-/* TODO: change log messages so that they get written to the result buffer */
+/** Flags passed to the add command. */
+enum com_add_flags {
+       /** Skip paths that exist already. */
+       ADD_FLAG_LAZY = 1,
+       /** Force adding. */
+       ADD_FLAG_FORCE = 2,
+       /** Print what is being done. */
+       ADD_FLAG_VERBOSE = 4,
+       /** Try to add files with unknown suffixes. */
+       ADD_FLAG_ALL = 8,
+};
 
 static int com_add_callback(const struct osl_object *query,
-               __a_unused struct osl_object *result)
+               struct osl_object *result)
 {
        char *buf = query->data, *path;
        struct osl_row *pb, *aft_row;
@@ -1257,6 +1396,7 @@ static int com_add_callback(const struct osl_object *query,
        char afsi_buf[AFSI_SIZE];
        uint32_t flags = read_u32(buf + AFTROW_FLAGS_OFFSET);
        struct afs_info default_afsi = {.last_played = 0};
+       struct para_buffer msg = {.buf = NULL};
 
        hash = (HASH_TYPE *)buf + AFTROW_HASH_OFFSET;
        hash_to_asc(hash, asc);;
@@ -1267,36 +1407,37 @@ static int com_add_callback(const struct osl_object *query,
        objs[AFTCOL_PATH].data = path;
        objs[AFTCOL_PATH].size = strlen(path) + 1;
 
-       PARA_DEBUG_LOG("request to add %s with hash %s\n", path, asc);
+       PARA_INFO_LOG("request to add %s\n", path);
        hs = find_hash_sister(hash);
        ret = aft_get_row_of_path(path, &pb);
        if (ret < 0 && ret != -E_RB_KEY_NOT_FOUND)
                return ret;
        if (hs && pb && hs == pb && !(flags & ADD_FLAG_FORCE)) {
                if (flags & ADD_FLAG_VERBOSE)
-                       PARA_NOTICE_LOG("ignoring duplicate %p\n", path);
-               return 1;
+                       para_printf(&msg, "ignoring duplicate\n");
+               ret = 1;
+               goto out;
        }
        if (hs && hs != pb) {
                struct osl_object obj;
                if (pb) { /* hs trumps pb, remove pb */
                        if (flags & ADD_FLAG_VERBOSE)
-                               PARA_NOTICE_LOG("removing path brother\n");
+                               para_printf(&msg, "removing path brother\n");
                        ret = osl_del_row(audio_file_table, pb);
                        if (ret < 0)
-                               return ret;
+                               goto out;
                        pb = NULL;
                }
                /* file rename, update hs' path */
                ret = osl_get_object(audio_file_table, hs, AFTCOL_PATH, &obj);
                if (flags & ADD_FLAG_VERBOSE)
-                       PARA_NOTICE_LOG("rename %s -> %s\n", (char *)obj.data, path);
+                       para_printf(&msg, "renamed from %s\n", (char *)obj.data);
                ret = osl_update_object(audio_file_table, hs, AFTCOL_PATH,
                        &objs[AFTCOL_PATH]);
                if (ret < 0)
-                       return ret;
+                       goto out;
                if (!(flags & ADD_FLAG_FORCE))
-                       return ret;
+                       goto out;
        }
        /* no hs or force mode, child must have sent afhi */
        uint16_t afhi_offset = read_u16(buf + AFTROW_AFHI_OFFSET_POS);
@@ -1304,8 +1445,9 @@ static int com_add_callback(const struct osl_object *query,
 
        objs[AFTCOL_AFHI].data = buf + afhi_offset;
        objs[AFTCOL_AFHI].size = chunks_offset - afhi_offset;
+       ret = -E_NO_AFHI;
        if (!objs[AFTCOL_AFHI].size) /* "impossible" */
-               return -E_NO_AFHI;
+               goto out;
        objs[AFTCOL_CHUNKS].data = buf + chunks_offset;
        objs[AFTCOL_CHUNKS].size = query->size - chunks_offset;
        if (pb && !hs) { /* update pb's hash */
@@ -1313,49 +1455,48 @@ static int com_add_callback(const struct osl_object *query,
                HASH_TYPE *old_hash;
                ret = get_hash_of_row(pb, &old_hash);
                if (ret < 0)
-                       return ret;
+                       goto out;
                hash_to_asc(old_hash, old_asc);
                if (flags & ADD_FLAG_VERBOSE)
-                       PARA_NOTICE_LOG("file change: %s %s -> %s\n", path,
+                       para_printf(&msg, "file change: %s -> %s\n",
                                old_asc, asc);
                ret = osl_update_object(audio_file_table, pb, AFTCOL_HASH,
                        &objs[AFTCOL_HASH]);
                if (ret < 0)
-                       return ret;
+                       goto out;
        }
        if (hs || pb) { /* (hs != NULL and pb != NULL) implies hs == pb */
-               const void *row = pb? pb : hs;
+               const struct osl_row *row = pb? pb : hs;
                /* update afhi and chunk_table */
                if (flags & ADD_FLAG_VERBOSE)
-                       PARA_NOTICE_LOG("updating audio format handler info (%zd bytes)\n",
-                               objs[AFTCOL_AFHI].size);
+                       para_printf(&msg, "updating afhi and chunk table\n");
                ret = osl_update_object(audio_file_table, row, AFTCOL_AFHI,
                        &objs[AFTCOL_AFHI]);
                if (ret < 0)
-                       return ret;
-               if (flags & ADD_FLAG_VERBOSE)
-                       PARA_NOTICE_LOG("updating chunk table\n");
+                       goto out;
                ret = osl_update_object(audio_file_table, row, AFTCOL_CHUNKS,
                        &objs[AFTCOL_CHUNKS]);
-               if (ret < 0)
-                       return ret;
-               ret = mood_update_audio_file(row, NULL);
-               if (ret < 0)
-                       return ret;
+               goto out;
        }
        /* new entry, use default afsi */
+       if (flags & ADD_FLAG_VERBOSE)
+               para_printf(&msg, "new file\n");
        default_afsi.last_played = time(NULL) - 365 * 24 * 60 * 60;
        default_afsi.audio_format_id = read_u8(buf + AFTROW_AUDIO_FORMAT_OFFSET);
 
-       if (flags & ADD_FLAG_VERBOSE)
-               PARA_NOTICE_LOG("adding %s\n", path);
        objs[AFTCOL_AFSI].data = &afsi_buf;
        objs[AFTCOL_AFSI].size = AFSI_SIZE;
        save_afsi(&default_afsi, &objs[AFTCOL_AFSI]);
        ret = osl_add_and_get_row(audio_file_table, objs, &aft_row);
+out:
        if (ret < 0)
-               return ret;
-       return mood_update_audio_file(aft_row, NULL);
+               para_printf(&msg, "%s\n", PARA_STRERROR(-ret));
+       if (!msg.buf)
+               return 0;
+       result->data = msg.buf;
+       result->size = msg.size;
+       return 1;
+       // mood_update_audio_file(aft_row, NULL);
 }
 
 struct private_add_data {
@@ -1392,23 +1533,22 @@ static int hash_sister_callback(const struct osl_object *query,
        return 1;
 }
 
-static int add_one_audio_file(const char *arg, const void *private_data)
+static int add_one_audio_file(const char *path, const void *private_data)
 {
-       int ret;
+       int ret, ret2;
        uint8_t format_num = -1;
        const struct private_add_data *pad = private_data;
        struct audio_format_info afhi, *afhi_ptr = NULL;
        struct osl_row *pb = NULL, *hs = NULL; /* path brother/hash sister */
        struct osl_object map, obj = {.data = NULL}, query, result;
-       char *path = NULL;
        HASH_TYPE hash[HASH_SIZE];
 
        afhi.header_offset = 0;
        afhi.header_len = 0;
-       ret = verify_path(arg, &path);
-       if (ret < 0)
+       ret = guess_audio_format(path);
+       if (ret < 0 && !(pad->flags & ADD_FLAG_ALL))
                goto out_free;
-       query.data = path;
+       query.data = (char *)path;
        query.size = strlen(path) + 1;
        ret = send_callback_request(path_brother_callback, &query, &result);
        if (ret < 0 && ret != -E_RB_KEY_NOT_FOUND)
@@ -1444,7 +1584,7 @@ static int add_one_audio_file(const char *arg, const void *private_data)
        if (pb && hs && hs == pb && (!(pad->flags & ADD_FLAG_FORCE))) {
                if (pad->flags & ADD_FLAG_VERBOSE)
                        ret = send_va_buffer(pad->fd,
-                               "not forcing update: %s\n", path);
+                               "%s exists, not forcing update\n", path);
                goto out_unmap;
        }
        /*
@@ -1458,23 +1598,34 @@ static int add_one_audio_file(const char *arg, const void *private_data)
                format_num = ret;
                afhi_ptr = &afhi;
        }
+       if (pad->flags & ADD_FLAG_VERBOSE) {
+               ret = send_va_buffer(pad->fd, "adding %s\n", path);
+               if (ret < 0)
+                       goto out_unmap;
+       }
        munmap(map.data, map.size);
        save_audio_file_info(hash, path, afhi_ptr, pad->flags, format_num, &obj);
        /* Ask afs to consider this entry for adding. */
-       ret = send_callback_request(com_add_callback, &obj, NULL);
+       ret = send_callback_request(com_add_callback, &obj, &result);
+       if (result.data && result.size) {
+               ret2 = send_va_buffer(pad->fd, "%s", (char *)result.data);
+               free(result.data);
+               if (ret >= 0 && ret2 < 0)
+                       ret = ret2;
+       }
        goto out_free;
 
 out_unmap:
        munmap(map.data, map.size);
 out_free:
-       if (ret < 0)
-               send_va_buffer(pad->fd, "failed to add %s (%s)\n", path?
-                       path : arg, PARA_STRERROR(-ret));
+       if (ret < 0 && ret != -E_SEND)
+               send_va_buffer(pad->fd, "failed to add %s (%s)\n", path,
+                       PARA_STRERROR(-ret));
        free(obj.data);
-       free(path);
        if (afhi_ptr)
                free(afhi_ptr->chunk_table);
-       return 1; /* it's not an error if not all files could be added */
+       /* it's not an error if not all files could be added */
+       return ret == -E_SEND? ret : 1;
 }
 
 int com_add(int fd, int argc, char * const * const argv)
@@ -1483,7 +1634,6 @@ int com_add(int fd, int argc, char * const * const argv)
        struct private_add_data pad = {.fd = fd, .flags = 0};
        struct stat statbuf;
 
-       PARA_NOTICE_LOG("argv[1]: %s\n", argv[1]);
        for (i = 1; i < argc; i++) {
                const char *arg = argv[i];
                if (arg[0] != '-')
@@ -1492,6 +1642,10 @@ int com_add(int fd, int argc, char * const * const argv)
                        i++;
                        break;
                }
+               if (!strcmp(arg, "-a")) {
+                       pad.flags |= ADD_FLAG_ALL;
+                       continue;
+               }
                if (!strcmp(arg, "-l")) {
                        pad.flags |= ADD_FLAG_LAZY;
                        continue;
@@ -1508,81 +1662,138 @@ int com_add(int fd, int argc, char * const * const argv)
        if (argc <= i)
                return -E_AFT_SYNTAX;
        for (; i < argc; i++) {
-               char *path = para_strdup(argv[i]);
-               size_t len = strlen(path);
-               while (len > 1 && path[--len] == '/')
-                       path[len] = '\0';
+               char *path;
+               ret = verify_path(argv[i], &path);
+               if (ret < 0) {
+                       ret = send_va_buffer(fd, "%s: %s\n", argv[i], PARA_STRERROR(-ret));
+                       if (ret < 0)
+                               return ret;
+                       continue;
+               }
                ret = stat(path, &statbuf);
-               if (ret < 0)
-                       PARA_NOTICE_LOG("failed to stat %s (%s)", path,
+               if (ret < 0) {
+                       ret = send_va_buffer(fd, "failed to stat %s (%s)\n", path,
                                strerror(errno));
+                       free(path);
+                       if (ret < 0)
+                               return ret;
+                       continue;
+               }
+               if (S_ISDIR(statbuf.st_mode))
+                       ret = for_each_file_in_dir(path, add_one_audio_file,
+                               &pad);
                else
-                       if (S_ISDIR(statbuf.st_mode))
-                               for_each_file_in_dir(path, add_one_audio_file,
-                                       &pad);
-                       else
-                               add_one_audio_file(path, &pad);
+                       ret = add_one_audio_file(path, &pad);
+               if (ret < 0) {
+                       send_va_buffer(fd, "%s: %s\n", path, PARA_STRERROR(-ret));
+                       free(path);
+                       return ret;
+               }
                free(path);
        }
-       ret = 1;
-       return ret;
+       return 1;
 
 }
 
+/**
+ * Flags used by the touch command.
+ *
+ * \sa com_touch().
+ */
+enum touch_flags {
+       /** Whether the \p FNM_PATHNAME flag should be passed to fnmatch(). */
+       TOUCH_FLAG_FNM_PATHNAME = 1,
+       /** Activates verbose mode. */
+       TOUCH_FLAG_VERBOSE = 2
+};
+
 struct com_touch_options {
-       long num_played;
-       long last_played;
-       long lyrics_id;
-       long image_id;
+       int32_t num_played;
+       int64_t last_played;
+       int32_t lyrics_id;
+       int32_t image_id;
+       unsigned flags;
 };
 
-static int com_touch_callback(const struct osl_object *query,
-               __a_unused struct osl_object *result)
-{
-       struct com_touch_options *cto = query->data;
-       char *p = (char *)query->data + sizeof(*cto);
-       size_t len;
-       int ret, no_options = cto->num_played < 0 && cto->last_played < 0 &&
-               cto->lyrics_id < 0 && cto->image_id < 0;
+struct touch_action_data {
+       struct com_touch_options *cto;
+       struct para_buffer pb;
+};
 
-       for (;p < (char *)query->data + query->size; p += len + 1) {
-               struct afs_info old_afsi, new_afsi;
-               struct osl_object obj;
-               struct osl_row *row;
+static int touch_audio_file(__a_unused struct osl_table *table,
+               struct osl_row *row, const char *name, void *data)
+{
+       struct touch_action_data *tad = data;
+       struct osl_object obj;
+       struct afs_info old_afsi, new_afsi;
+       int ret, no_options = tad->cto->num_played < 0 && tad->cto->last_played < 0 &&
+               tad->cto->lyrics_id < 0 && tad->cto->image_id < 0;
 
-               len = strlen(p);
-               ret = aft_get_row_of_path(p, &row);
-               if (ret < 0)
-                       return ret;
-               ret = get_afsi_object_of_row(row, &obj);
-               if (ret < 0)
-                       return ret;
-               ret = load_afsi(&old_afsi, &obj);
-               if (ret < 0)
-                       return ret;
-               new_afsi = old_afsi;
-               if (no_options) {
-                       new_afsi.num_played++;
-                       new_afsi.last_played = time(NULL);
-               } else {
-                       if (cto->lyrics_id >= 0)
-                               new_afsi.lyrics_id = cto->lyrics_id;
-                       if (cto->image_id >= 0)
-                               new_afsi.image_id = cto->image_id;
-                       if (cto->num_played >= 0)
-                               new_afsi.num_played = cto->num_played;
-                       if (cto->last_played >= 0)
-                               new_afsi.last_played = cto->last_played;
-               }
-               save_afsi(&new_afsi, &obj); /* in-place update */
-               ret = mood_update_audio_file(row, &old_afsi);
-               if (ret < 0)
-                       return ret;
+       ret = get_afsi_object_of_row(row, &obj);
+       if (ret < 0) {
+               para_printf(&tad->pb, "%s: %s\n", name, PARA_STRERROR(-ret));
+               return 1;
+       }
+       ret = load_afsi(&old_afsi, &obj);
+       if (ret < 0) {
+               para_printf(&tad->pb, "%s: %s\n", name, PARA_STRERROR(-ret));
+               return 1;
        }
+       new_afsi = old_afsi;
+       if (no_options) {
+               new_afsi.num_played++;
+               new_afsi.last_played = time(NULL);
+               if (tad->cto->flags & TOUCH_FLAG_VERBOSE)
+                       para_printf(&tad->pb, "%s: num_played = %u, "
+                               "last_played = now()\n", name,
+                               new_afsi.num_played);
+       } else {
+               if (tad->cto->flags & TOUCH_FLAG_VERBOSE)
+                       para_printf(&tad->pb, "touching %s\n", name);
+               if (tad->cto->lyrics_id >= 0)
+                       new_afsi.lyrics_id = tad->cto->lyrics_id;
+               if (tad->cto->image_id >= 0)
+                       new_afsi.image_id = tad->cto->image_id;
+               if (tad->cto->num_played >= 0)
+                       new_afsi.num_played = tad->cto->num_played;
+               if (tad->cto->last_played >= 0)
+                       new_afsi.last_played = tad->cto->last_played;
+       }
+       save_afsi(&new_afsi, &obj); /* in-place update */
+       ret = mood_update_audio_file(row, &old_afsi);
+       if (ret < 0)
+               para_printf(&tad->pb, "%s: %s\n", name, PARA_STRERROR(-ret));
        return 1;
 }
 
-int com_touch(__a_unused int fd, int argc, char * const * const argv)
+static int com_touch_callback(const struct osl_object *query,
+               struct osl_object *result)
+{
+       struct touch_action_data tad = {.cto = query->data};
+       int ret;
+       struct pattern_match_data pmd = {
+               .table = audio_file_table,
+               .loop_col_num = AFTCOL_HASH,
+               .match_col_num = AFTCOL_PATH,
+               .patterns = {.data = (char *)query->data + sizeof(*tad.cto),
+                       .size = query->size - sizeof(*tad.cto)},
+               .data = &tad,
+               .action = touch_audio_file
+       };
+       if (tad.cto->flags & TOUCH_FLAG_FNM_PATHNAME)
+               pmd.fnmatch_flags |= FNM_PATHNAME;
+       ret = for_each_matching_row(&pmd);
+       if (ret < 0)
+               para_printf(&tad.pb, "%s\n", PARA_STRERROR(-ret));
+       if (tad.pb.buf) {
+               result->data = tad.pb.buf;
+               result->size = tad.pb.size;
+               return 1;
+       }
+       return ret < 0? ret : 0;
+}
+
+int com_touch(int fd, int argc, char * const * const argv)
 {
        struct com_touch_options cto = {
                .num_played = -1,
@@ -1590,7 +1801,8 @@ int com_touch(__a_unused int fd, int argc, char * const * const argv)
                .lyrics_id = -1,
                .image_id = -1
        };
-       struct osl_object options = {.data = &cto, .size = sizeof(cto)};
+       struct osl_object query = {.data = &cto, .size = sizeof(cto)},
+               result;
        int i, ret;
 
 
@@ -1603,79 +1815,259 @@ int com_touch(__a_unused int fd, int argc, char * const * const argv)
                        break;
                }
                if (!strncmp(arg, "-n", 2)) {
-                       ret = para_atol(arg + 2, &cto.num_played);
+                       ret = para_atoi32(arg + 2, &cto.num_played);
                        if (ret < 0)
-                               goto err;
+                               return ret;
                        continue;
                }
                if (!strncmp(arg, "-l", 2)) {
-                       ret = para_atol(arg + 2, &cto.last_played);
+                       ret = para_atoi64(arg + 2, &cto.last_played);
                        if (ret < 0)
-                               goto err;
+                               return ret;
                        continue;
                }
                if (!strncmp(arg, "-y", 2)) {
-                       ret = para_atol(arg + 2, &cto.lyrics_id);
+                       ret = para_atoi32(arg + 2, &cto.lyrics_id);
                        if (ret < 0)
-                               goto err;
+                               return ret;
                        continue;
                }
                if (!strncmp(arg, "-i", 2)) {
-                       ret = para_atol(arg + 2, &cto.image_id);
+                       ret = para_atoi32(arg + 2, &cto.image_id);
                        if (ret < 0)
-                               goto err;
+                               return ret;
+                       continue;
+               }
+               if (!strcmp(arg, "-p")) {
+                       cto.flags |= TOUCH_FLAG_FNM_PATHNAME;
                        continue;
                }
+               if (!strcmp(arg, "-v")) {
+                       cto.flags |= TOUCH_FLAG_VERBOSE;
+                       continue;
+               }
+               break; /* non-option starting with dash */
        }
-       ret = -E_AFT_SYNTAX;
        if (i >= argc)
-               goto err;
-       return send_option_arg_callback_request(&options, argc - i,
-               argv + i, com_touch_callback, NULL);
-err:
+               return -E_AFT_SYNTAX;
+       ret = send_option_arg_callback_request(&query, argc - i,
+               argv + i, com_touch_callback, &result);
+       if (ret > 0) {
+               send_buffer(fd, (char *)result.data);
+               free(result.data);
+       } else
+               send_va_buffer(fd, "%s\n", PARA_STRERROR(-ret));
        return ret;
 }
 
-struct com_rm_options {
+enum rm_flags {
+       RM_FLAG_VERBOSE = 1,
+       RM_FLAG_FORCE = 2,
+       RM_FLAG_FNM_PATHNAME = 4
+};
+
+struct com_rm_data {
        uint32_t flags;
+       struct para_buffer pb;
+       unsigned num_removed;
 };
 
+static int remove_audio_file(__a_unused struct osl_table *table,
+               struct osl_row *row, const char *name, void *data)
+{
+       struct com_rm_data *crd = data;
+       int ret;
+
+       if (crd->flags & RM_FLAG_VERBOSE)
+               para_printf(&crd->pb, "removing %s\n", name);
+       ret = mood_delete_audio_file(row);
+       if (ret < 0)
+               para_printf(&crd->pb, "%s: %s\n", name, PARA_STRERROR(-ret));
+       ret = osl_del_row(audio_file_table, row);
+       if (ret < 0)
+               para_printf(&crd->pb, "%s: %s\n", name, PARA_STRERROR(-ret));
+       else
+               crd->num_removed++;
+       return 1;
+}
+
 static int com_rm_callback(const struct osl_object *query,
                __a_unused struct osl_object *result)
 {
-       struct com_rm_options *cro = query->data;
-       char *p = (char *)query->data + sizeof(*cro);
-       size_t len;
+       struct com_rm_data crd = {.flags = *(uint32_t *)query->data};
        int ret;
+       struct pattern_match_data pmd = {
+               .table = audio_file_table,
+               .loop_col_num = AFTCOL_HASH,
+               .match_col_num = AFTCOL_PATH,
+               .patterns = {.data = (char *)query->data + sizeof(uint32_t),
+                       .size = query->size - sizeof(uint32_t)},
+               .data = &crd,
+               .action = remove_audio_file
+       };
+       if (crd.flags & RM_FLAG_FNM_PATHNAME)
+               pmd.fnmatch_flags |= FNM_PATHNAME;
+       ret = for_each_matching_row(&pmd);
+       if (ret < 0)
+               para_printf(&crd.pb, "%s\n", PARA_STRERROR(-ret));
+       if (!crd.num_removed && !(crd.flags & RM_FLAG_FORCE))
+               para_printf(&crd.pb, "no matches -- nothing removed\n");
+       else {
+               if (crd.flags & RM_FLAG_VERBOSE)
+                       para_printf(&crd.pb, "removed %u files\n", crd.num_removed);
+       }
+       if (crd.pb.buf) {
+               result->data = crd.pb.buf;
+               result->size = crd.pb.size;
+               return 1;
+       }
+       return ret < 0? ret : 0;
+}
 
-       for (;p < (char *)query->data + query->size; p += len + 1) {
-               struct osl_row *row;
+/* TODO options: -r (recursive) */
+int com_afs_rm(int fd, int argc,  char * const * const argv)
+{
+       uint32_t flags = 0;
+       struct osl_object query = {.data = &flags, .size = sizeof(flags)},
+               result;
+       int i, ret;
 
-               len = strlen(p);
-               ret = aft_get_row_of_path(p, &row);
-               if (ret < 0)
-                       return ret;
-               ret = mood_delete_audio_file(row);
-               if (ret < 0)
-                       return ret;
-               ret = osl_del_row(audio_file_table, row);
-               if (ret < 0)
-                       return ret;
+       for (i = 1; i < argc; i++) {
+               const char *arg = argv[i];
+               if (arg[0] != '-')
+                       break;
+               if (!strcmp(arg, "--")) {
+                       i++;
+                       break;
+               }
+               if (!strcmp(arg, "-f")) {
+                       flags |= RM_FLAG_FORCE;
+                       continue;
+               }
+               if (!strcmp(arg, "-p")) {
+                       flags |= RM_FLAG_FNM_PATHNAME;
+                       continue;
+               }
+               if (!strcmp(arg, "-v")) {
+                       flags |= RM_FLAG_VERBOSE;
+                       continue;
+               }
+               break;
        }
-       return 1;
+       if (i >= argc)
+               return -E_AFT_SYNTAX;
+       ret = send_option_arg_callback_request(&query, argc - i, argv + i,
+               com_rm_callback, &result);
+       if (ret > 0) {
+               send_buffer(fd, (char *)result.data);
+               free(result.data);
+       } else
+               send_va_buffer(fd, "%s\n", PARA_STRERROR(-ret));
+       return ret;
 }
 
-/*
- * TODO options: -v verbose, -f dont stop if file not found
- * -h remove by hash, use fnmatch
+/**
+ * Flags used by the cpsi command.
  *
- * */
+ * \sa com_cpsi().
+ */
+enum cpsi_flags {
+       /** Whether the lyrics id should be copied. */
+       CPSI_FLAG_COPY_LYRICS_ID = 1,
+       /** Whether the image id should be copied. */
+       CPSI_FLAG_COPY_IMAGE_ID = 2,
+       /** Whether the lastplayed time should be copied. */
+       CPSI_FLAG_COPY_LASTPLAYED = 4,
+       /** Whether the numplayed count should be copied. */
+       CPSI_FLAG_COPY_NUMPLAYED = 8,
+       /** Whether the attributes should be copied. */
+       CPSI_FLAG_COPY_ATTRIBUTES = 16,
+       /** Activates verbose mode. */
+       CPSI_FLAG_VERBOSE = 32,
+};
+
+struct cpsi_action_data {
+       unsigned flags;
+       unsigned num_copied;
+       struct para_buffer pb;
+       struct afs_info source_afsi;
+};
+
+static int copy_selector_info(__a_unused struct osl_table *table,
+               struct osl_row *row, const char *name, void *data)
+{
+       struct cpsi_action_data *cad = data;
+       struct osl_object target_afsi_obj;
+       int ret;
+       struct afs_info target_afsi;
+
+       ret = get_afsi_object_of_row(row, &target_afsi_obj);
+       if (ret < 0)
+               return ret;
+       load_afsi(&target_afsi, &target_afsi_obj);
+       if (cad->flags & CPSI_FLAG_COPY_LYRICS_ID)
+               target_afsi.lyrics_id = cad->source_afsi.lyrics_id;
+       if (cad->flags & CPSI_FLAG_COPY_IMAGE_ID)
+               target_afsi.image_id = cad->source_afsi.image_id;
+       if (cad->flags & CPSI_FLAG_COPY_LASTPLAYED)
+               target_afsi.last_played = cad->source_afsi.last_played;
+       if (cad->flags & CPSI_FLAG_COPY_NUMPLAYED)
+               target_afsi.num_played = cad->source_afsi.num_played;
+       if (cad->flags & CPSI_FLAG_COPY_ATTRIBUTES)
+               target_afsi.attributes = cad->source_afsi.attributes;
+       save_afsi(&target_afsi, &target_afsi_obj); /* in-place update */
+       cad->num_copied++;
+       if (cad->flags & CPSI_FLAG_VERBOSE)
+               para_printf(&cad->pb, "copied afsi to %s\n", name);
+       return 1;
+}
+
+static int com_cpsi_callback(const struct osl_object *query,
+               struct osl_object *result)
+{
+       struct cpsi_action_data cad = {.flags = *(unsigned *)query->data};
+       int ret;
+       char *source_path = (char *)query->data + sizeof(cad.flags);
+
+       ret = get_afsi_of_path(source_path, &cad.source_afsi);
+       if (ret < 0)
+               goto out;
+       struct pattern_match_data pmd = {
+               .table = audio_file_table,
+               .loop_col_num = AFTCOL_HASH,
+               .match_col_num = AFTCOL_PATH,
+               .patterns = {.data = source_path + strlen(source_path) + 1,
+                       .size = query->size - sizeof(cad.flags)
+                               - strlen(source_path) - 1},
+               .data = &cad,
+               .action = copy_selector_info
+       };
+       ret = for_each_matching_row(&pmd);
+out:
+       if (ret < 0)
+               para_printf(&cad.pb, "%s\n", PARA_STRERROR(-ret));
+       if (cad.flags & CPSI_FLAG_VERBOSE) {
+               if (cad.num_copied)
+                       para_printf(&cad.pb, "copied requested afsi from %s "
+                               "to %u files\n",
+                               source_path, cad.num_copied);
+               else
+                       para_printf(&cad.pb, "nothing copied\n");
+       }
+       if (cad.pb.buf) {
+               result->data = cad.pb.buf;
+               result->size = cad.pb.size;
+               return 1;
+       }
+       return ret < 0? ret : 0;
+}
 
-int com_afs_rm(__a_unused int fd, int argc,  char * const * const argv)
+int com_cpsi(int fd, int argc,  char * const * const argv)
 {
-       struct com_rm_options cro = {.flags = 0};
-       struct osl_object options = {.data = &cro, .size = sizeof(cro)};
+       unsigned flags = 0;
        int i, ret;
+       struct osl_object options = {.data = &flags, .size = sizeof(flags)},
+               result;
 
        for (i = 1; i < argc; i++) {
                const char *arg = argv[i];
@@ -1685,16 +2077,104 @@ int com_afs_rm(__a_unused int fd, int argc,  char * const * const argv)
                        i++;
                        break;
                }
+               if (!strcmp(arg, "-y")) {
+                       flags |= CPSI_FLAG_COPY_LYRICS_ID;
+                       continue;
+               }
+               if (!strcmp(arg, "-i")) {
+                       flags |= CPSI_FLAG_COPY_IMAGE_ID;
+                       continue;
+               }
+               if (!strcmp(arg, "-l")) {
+                       flags |= CPSI_FLAG_COPY_LASTPLAYED;
+                       continue;
+               }
+               if (!strcmp(arg, "-n")) {
+                       flags |= CPSI_FLAG_COPY_NUMPLAYED;
+                       continue;
+               }
+               if (!strcmp(arg, "-a")) {
+                       flags |= CPSI_FLAG_COPY_ATTRIBUTES;
+                       continue;
+               }
+               if (!strcmp(arg, "-v")) {
+                       flags |= CPSI_FLAG_VERBOSE;
+                       continue;
+               }
+               break;
        }
-       ret = -E_AFT_SYNTAX;
-       if (i >= argc)
-               goto err;
-       return send_option_arg_callback_request(&options, argc - i,
-               argv + i, com_rm_callback, NULL);
-err:
+       if (i + 1 >= argc) /* need at least souce file and pattern */
+               return -E_AFT_SYNTAX;
+       if (!(flags & ~CPSI_FLAG_VERBOSE)) /* no copy flags given */
+               flags = ~(unsigned)CPSI_FLAG_VERBOSE | flags;
+       ret = send_option_arg_callback_request(&options, argc - i, argv + i,
+               com_cpsi_callback, &result);
+       if (ret > 0) {
+               send_buffer(fd, (char *)result.data);
+               free(result.data);
+       } else
+               send_va_buffer(fd, "%s\n", PARA_STRERROR(-ret));
        return ret;
 }
 
+/* TODO: optionally fix problems by removing offending rows */
+static int check_audio_file(struct osl_row *row, void *data)
+{
+       char *path;
+       struct para_buffer *pb = data;
+       struct stat statbuf;
+       int ret = get_audio_file_path_of_row(row, &path);
+       struct afs_info afsi;
+       char *blob_name;
+
+       if (ret < 0) {
+               para_printf(pb, "%s\n", PARA_STRERROR(-ret));
+               return 1;
+       }
+       if (stat(path, &statbuf) < 0)
+               para_printf(pb, "%s: stat error (%s)\n", path, strerror(errno));
+       else {
+               if (!S_ISREG(statbuf.st_mode))
+                       para_printf(pb, "%s: not a regular file\n", path);
+       }
+       ret = get_afsi_of_row(row, &afsi);
+       if (ret < 0) {
+               para_printf(pb, "%s: %s\n", path, PARA_STRERROR(-ret));
+               return 1;
+       }
+       ret = lyr_get_name_by_id(afsi.lyrics_id, &blob_name);
+       if (ret < 0)
+               para_printf(pb, "%s lyrics id %u: %s\n", path, afsi.lyrics_id,
+                       PARA_STRERROR(-ret));
+       ret = img_get_name_by_id(afsi.image_id, &blob_name);
+       if (ret < 0)
+               para_printf(pb, "%s image id %u: %s\n", path, afsi.image_id,
+                       PARA_STRERROR(-ret));
+       return 1;
+}
+
+/**
+ * Check the audio file table for inconsistencies.
+ *
+ * \param query Unused.
+ * \param result Contains message string upon return.
+ *
+ * This function always succeeds.
+ *
+ * \sa com_check().
+ */
+int aft_check_callback(__a_unused const struct osl_object *query, struct osl_object *result)
+{
+       struct para_buffer pb = {.buf = NULL};
+
+       para_printf(&pb, "checking audio file table...\n");
+       audio_file_loop(&pb, check_audio_file);
+       result->data = pb.buf;
+       result->size = pb.size;
+       return 1;
+
+}
+
 /**
  * Close the audio file table.
  *
@@ -1702,36 +2182,50 @@ err:
  *
  * \sa osl_close_table().
  */
-void aft_shutdown(enum osl_close_flags flags)
+static void aft_close(void)
 {
-       osl_close_table(audio_file_table, flags);
+       osl_close_table(audio_file_table, OSL_MARK_CLEAN);
+       audio_file_table = NULL;
 }
 
 /**
  * Open the audio file table.
  *
- * \param ti Gets initialized by this function.
- * \param db The database directory.
+ * \param dir The database directory.
  *
- * \return Positive on success, negative on errors.
+ * \return Standard.
  *
  * \sa osl_open_table().
  */
-int aft_init(struct table_info *ti, const char *db)
+static int aft_open(const char *dir)
 {
        int ret;
 
-       audio_file_table_desc.dir = db;
-       ti->desc = &audio_file_table_desc;
-       ret = osl_open_table(ti->desc, &ti->table);
+       audio_file_table_desc.dir = dir;
+       ret = osl_open_table(&audio_file_table_desc, &audio_file_table);
        if (ret >= 0) {
                unsigned num;
-               audio_file_table = ti->table;
                osl_get_num_rows(audio_file_table, &num);
                PARA_INFO_LOG("audio file table contains %d files\n", num);
                return ret;
        }
        PARA_INFO_LOG("failed to open audio file table\n");
        audio_file_table = NULL;
-       return ret == -E_NOENT? 1 : ret;
+       if (ret >= 0 || is_errno(-ret, ENOENT))
+               return 1;
+       return ret;
+}
+
+static int aft_create(const char *dir)
+{
+       audio_file_table_desc.dir = dir;
+       return osl_create_table(&audio_file_table_desc);
+}
+
+void aft_init(struct afs_table *t)
+{
+       t->name = audio_file_table_desc.name;
+       t->open = aft_open;
+       t->close = aft_close;
+       t->create = aft_create;
 }