#!/bin/ksh
INPUT_DIR="/transcode-input"
OUTPUT_DIR="/transcode-output"

while true; do
  find "$INPUT_DIR" -type f ! -name '*.lock' |sort --random-sort |{
    while read file; do
      file_lock="$file.lock"
      if [ ! -f "$file_lock" ]; then
        break
      fi
    done
  }

  # No more files to process
  if [ -z "$file" ]; then
    halt
    exit
  fi

  file_noext="`echo "$file" |sed 's/\(.*\)\..*/\1/'`"
  file_out="$OUTPUT_DIR/`basename "$file_noext.mp4"`"
  file_orig_out="$OUTPUT_DIR/`basename "$file"`"

  if [ ! -f "$file_lock" ]; then
    touch "$file_lock"
    mv "$file" "$file_orig_out"
    rm "$file_lock"

    ffmpeg -i "$file_orig_out" -vcodec libxvid -flags +aic+cbp+mv0+mv4 -mbd 2 -cmp 2 -subcmp 2 -g 250 -bufsize 2M -b 1200k -maxrate 2.5M -ab 128k -threads `cat /proc/cpuinfo |grep -c '^processor'` -acodec libfaac "$file_out" >> "$file_orig_out.log" 2>&1
  fi

  sleep 1
done

