#!/bin/sh

# Copyright (C) 2008 Jonathan Moore Liles                                     #
#                                                                             #
# 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 2 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; see the file COPYING.  If not,write to the Free Software #
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  #

## import-external-sources
#
# June 2008, Jonathan Moore Liles
#
# Simple script to scan a compacted Non-DAW project and copy external
# sources into the project directory.
#
# USAGE:
#
#     $ import-external-sources ~/audio/'The Best Song Ever'

DRY_RUN=no
ONLY_COMPACTED=no

fatal ()
{
    echo Error: "$1"
    echo 'Aborting!'
    cleanup
    exit 1
}

cleanup ()
{
    rm -f "${TEMP}/external-sources"
}

import_sources ()
{
    local FILE
    while read FILE
    do
        if [ $DRY_RUN = yes ]
        then
            echo "Would import: ${FILE}"
        else
            echo "Importing source \"${FILE}\"..."
            cp "${FILE}" sources
            [ -f "${FILE}.peak" ] && cp "${FILE}.peak" sources

            ( echo "%s':source \"${FILE}\"':source \"${FILE##*/}\"'"; echo -e "\nwq" ) |
            ed -s "history"
        fi
    done
}

[ $# -gt 0 ] || fatal "Usage: $0 [--dry-run] path/to/project"

if [ "$1" = --dry-run ]
then
    DRY_RUN=yes
    shift 1
fi

PROJECT="$1"

cd "$PROJECT" || fatal "No such project"

[ -f history ] && [ -f info ] || fatal "Not a Non-DAW project?"

[ -f .lock ] && fatal "Project appears to be in use"

if [ $ONLY_COMPACTED = yes ]
then
    grep -v '\(^\{\|\}$\)\|create' history && fatal "Not a compacted project"
fi

echo "Scanning \"${PROJECT}\"..."

sed -n 's/^\s*Audio_Region .* create :source "\([^"]\+\)".*$/\1/; /^\//p' history | sort | uniq > "${TEMP}/external-sources"

import_sources < "${TEMP}/external-sources"

cleanup

echo "Done."
