#!/bin/bash

baseDir="/home/yggdrasil/Videos/Shows"

# Helptext
function usage() {
    echo Sort files from /home/yggdrasil/new_acquisition into appropriate show directories.
    echo
    echo Usage: $0 '[ -h ] [ -f fileToUse ] [ -c ] [ -n ] [ -q ] [ -v ]'
    echo '  -c: Create sample sort file'
    echo '  -f: Use this sort file'
    echo '  -h: print this helptext.'
    echo '  -n: Do not lock the libary -- this is useful for sorting other things after execution.'
    echo '  -q: Mute output'
    echo '  -v: Increase verbosity'
}

# Handle a file
# param file: the file to parse
function HandleFile() {
    file="$1"
    # Sort out file metadata
    dirtyshowname="$(echo "$file" | sed 's/.[Ss][0-9].[Ee][0-9].*$//')"
    showname="$(ls -1 "$baseDir" | grep -E -i "$dirtyshowname")"
    epinfo="$(echo "$file" | sed "s/^${dirtyshowname}.//" | head -c 6)"
    season="$(echo "$epinfo" | head -c 3 | tail -c 2)"
    episode="$(echo -n "$epinfo" | tail -c 2)"
    target="$baseDir"/"$showname"/Season\ "$season"
    # Ensure metadata sorting didn't return nulls
    for i in dirtyshowname showname epinfo season episode target; do
        if [ -z "${!i}" ]; then
            echo ERROR: Could not handle "$file" because we could not find $i
            return
        fi
    done
    # Make sure target exists
    # Move file to target
    if [ ! -d "$(dirname "$target")" ]; then
        echo WARN -- could not find the right show to sort "$file"
    fi
    # Make sure the show folder exists
    mkdir -p "$target"
    mv "$file" "$target"
}


# Parse arguments.
while getopts 'b:cf:hnqv' OPTION; do
    case "$OPTION" in
        b) baseDir="${OPTARG}" ;;
        h) usage; exit 0 ;;
        l) exec $0 $(echo $@ | sed "s/-s\s+${OPTARG}(.|$)//") | tee -a "${OPTARG}" ;;
        n) nolock="1" ;;
        q) exec $0 $(echo $@ | sed 's/-q//') &>/dev/null ;;
        v) set -x ;;
        *) usage; exit 1 ;;
    esac
done

cd /home/yggdrasil/new_acquisition

echo INFO Unlocking filestore
if [ `whoami` != "root" ]; then yggdrasil-unlock; fi

echo INFO Sorting....
# Find all files matching *S??E??* syntax
ls -1d *[S,s]??[E,e]??* 2>/dev/null | while read file; do
     HandleFile "${file}"
done

if [ -z "$nolock" ] && [ `whoami` != "root" ]; then
    echo INFO Locking filestore
    yggdrasil-lock &>/dev/null
fi
