#!/bin/bash
#
# fixupm4a - a script to fix the metadata on broken .m4a files
#
# Copyright 2011 Jon Davies
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

if [ ! -z "$1" ]; then
  # fixup .m4a if required
  if [ -f "$1" ]; then
    m4afile=$1
    if [ "${m4afile##*.}" = "m4a" ]; then
      echo Fixing up $m4afile
      # clean up the tags and metadata with mp4tags
      artist=$(mp4info "$m4afile" | grep ^\ Artist\: | cut -c10-)
      mp4tags -a "$artist" "$m4afile"
      # optimize the m4a (moves the metadata to the front)
      # mp4creator does something with temporary files, and complains if
      # its working directory is on a different filesystem to the file
      # being optimised, so temporarily move to the same directory
      filedir=$(dirname "$m4afile")
      ( cd "$filedir" ; mp4creator -optimize "$m4afile" )
    fi
  fi
fi