#!/usr/bin/env bash

#*******************************************************************************
#
# Bare Conductive Pi Cap sample converter
# ---------------------------------------
#
# picap-samples-to-wav - converts set of *.mp3/*.ogg/*.m4p/*.whatever_probably 
#                        files into hashed wavs, for use with picap-touch-mp3-*
#
# Written by Szymon Kaliski.
#
# This work is licensed under a MIT license https://opensource.org/licenses/MIT
#
# Copyright (c) 2016, Bare Conductive
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
#*******************************************************************************

# init

OUT_DIR="$1"/.wavs/
declare -a HASH_FILES
mkdir -p "$OUT_DIR" > /dev/null 2>&1

# convert

pushd "$1" > /dev/null 2>&1

for i in *.{aac,AAC,ac3,AC3,aiff,AIFF,flac,FLAC,mp3,MP3}; do
  if [[ -f $i ]]; then
    HASH=$(md5sum "$i" | cut -d ' ' -f1)
    WAV_HASH=$HASH.wav
    WAV=$(echo "$i" | cut -d "." -f1).wav

    HASH_FILES+=($WAV_HASH)

    if [[ ! -f ".wavs/$WAV_HASH" ]]; then
      printf "no %s for %s, converting..." "$WAV_HASH" "$i"

      pushd ".wavs" > /dev/null 2>&1
      avconv -i "../$i" "$WAV_HASH" > /dev/null 2>&1
      rm "$WAV" > /dev/null 2>&1
      ln -s "$WAV_HASH" "$WAV"
      popd > /dev/null 2>&1

      printf " done!\n"
    fi
  fi
done

popd > /dev/null 2>&1

# cleanup

pushd "$OUT_DIR" > /dev/null 2>&1

for i in *.wav; do
  if [[ ! -L "$i" ]] && [[ ! " ${HASH_FILES[@]} " =~ " $i " ]]; then
    printf "extraneous file %s in .wavs, removing\n" "$i"
    rm -f "$i"
  fi
done

popd > /dev/null 2>&1
