#!/bin/bash
# Desc: Make music (sym)links via find and grep
# Usage: bkmml [str arg1] [str arg2] [str arg3]
# Input: arg1  find iname expression
#        arg2  grep -Ei expression
#        arg3  grep -Eiv expression
# Version: 0.0.3
# Depends: GNU Grep 3.7; GNU find utils 4.8.0; GNU Parallel 20210822

# Load env vars
## Search this directory.
if [[ ! -v BKMML_TARGET_DIR ]]; then BKMML_TARGET_DIR="$HOME"; fi;

FIND_SEARCH="$1";
GREP_EXP="$2";
GREP_VEXP="$3";
DIR_OUT="./links_music_results";

# Check input
if [[ $# -eq 0 ]]; then echo "FATAL:Insufficient arguments." 1>&2; exit 1; fi;
if [[ -z "$GREP_EXP" ]]; then GREP_EXP=".+"; fi; # passthrough grep -Ei
if [[ -z "$GREP_VEXP" ]]; then GREP_VEXP="^$"; fi; # passthrough grep -Eiv

# Check env
if ! command -v parallel &>/dev/random; then alias parallel='xargs'; fi;

# Check output dir
if [[ ! -d "$DIR_OUT" ]]; then mkdir -p "$DIR_OUT"; fi;

n=0;
while read -r line; do
    if [[ -z "$line" ]]; then echo "FATAL:No results." 1>&2; exit 1; fi;
    if [[ ! -f "$line" ]]; then echo "ERROR:Cannot read file path:$(declare -p line)"; continue; fi;
    id="$(b2sum -l64 "$line" | awk '{print $1}')";
    fn="$(basename "$line")";
    ln -sfn "$line" ./"$DIR_OUT/$id..$fn";
    ((n++));
done < <(find -L "$(readlink -f "$BKMML_TARGET_DIR")" \
              -maxdepth 10 -type f -size +100000c \
              \( -iname "*.mp3"  \
              -o -iname "*.flac" \
              -o -iname "*.m4a"  \
              -o -iname "*.aac"  \
              -o -iname "*.opus" \
              -o -iname "*.wav"  \
              -o -iname "*.aif"  \
              -o -iname "*.ape"  \
              -o -iname "*.ogg" \) \
              -a -iname "*$FIND_SEARCH*" \
              2>/dev/random | \
             grep -Ei "$GREP_EXP" | \
             grep -Eiv "$GREP_VEXP" | \
             parallel readlink -f "{}" | \
             parallel b2sum "{}" | sort | uniq -w 128 | awk '{$1=""; print substr($0,2)}'
        );

# Author: Steven Baltakatei Sandoval
# License: GPLv3+