#!/bin/sh

# This script takes not arguments

### CONF ###

INDIR="/encode/IN"
OUTDIR="/encode/OUT"
LOG="/encode/autoencode.log"

# FileNameConvention:
# [<audio channel>,<language>,resolution] - <title>.ext
# [1,DE,1080] - 23 - Nichts ist wie es scheint.mp4

log() {
    printf '%s: %s\n' "$(date +%Y%m%y.%H%M%S)" "$1" # >> $LOG
}

find "$INDIR" -type f | while read file;
do
    _base="$(basename "$file")"
    _track="$(printf '%s' "$_base" | sed 's/^\[\(.[^,]*\),.*\] - .*/\1/g')"
    _lang="$(printf '%s' "$_base" | sed 's/^\[.*,\(.*\),.*\] - .*/\1/g')"
    _size="$(printf '%s' "$_base" | sed 's/^\[.*,.*,\(.*\)] - .*/\1/g')"
    _title="$(printf '%s' "$_base" | sed 's/^\[.*,.*,.*\] - \(.*\)\..*/\1/g')"
    _out="$_title [${_lang}][${_size}p].mkv"

    log "File $_base"
    log "Track: $_track"
    log "Language: $_lang"
    log "Resolution: $_size"
    log "Title: $_title"
    log "Outfile: $_out"

    ffmpeg -loglevel error \
        -i "$file" \
        -c:a copy \
        -map 0:$_track \
        -c:v libx264 \
        -vf "scale=-2:$_size" \
        -crf 21 \
        -preset veryslow \
        -tune zerolatency \
        "$OUTDIR/$_out"
done
