#!/bin/sh

# MPlayer file loader : determines what to do with the chosen file
# usage: mp_loader file_location key_binding

cp_fifo=/var/cp_fifo
mp_fifo=/var/mp_control
op_fifo=/var/op_fifo

filter_file=/etc/file_ext
filter_playlist=/etc/list_ext
filter_image=/etc/img_ext
filter_cdvdimg=/etc/cdvdimg_ext

file=$1
key=$2
if [ "$key" = "u" ]; then
  append=1;
else
  append=0;
fi

if test -e "$file"; then
  ext=`echo "$file" | sed 's/.*\.\([^\.]*\)/\1/'`
  escfile=`echo "$file" | sed 's%\(\\\\\)%\1\1%g' | sed 's%"%\\\\"%g'`
  # File Operations
  if [ "$key" = "d" ]; then
    echo "cd $file" > $cp_fifo
  elif [ "$key" = "c" ]; then
    echo "cp $file" > $cp_fifo
  elif [ "$key" = "r" ]; then
    echo "rm $file" > $cp_fifo
  elif [ "$key" = "o" ]; then
    echo "rmok $file" > $cp_fifo
  elif [ -d "$file" ]; then
    if [ "$key" = "p" ]; then
      playdir "$file" || view_img -a "$file"
    elif [ "$key" = "l" ]; then
      playdir "$file" || view_img -r "$file"
    elif [ "$key" = "u" ]; then
      playdir "$file" $append
    fi
  elif [ "$key" = "b" -a -f "$file" ]; then
    echo -e "$file" > $op_fifo
  elif [ -n "$ext" ]; then
    # File Playback
    if test -e /var/mountimg && grep -iq "^$ext\$" $filter_cdvdimg; then
      [ -d /mnt/discimage ] || mkdir -p /mnt/discimage
      if `cat /proc/mounts | grep /dev/loop | grep -q /mnt/discimage`; then
        umount -d /mnt/discimage && rmdir /mnt/discimage || exit
      fi
      # fuseiso -n "$file" /mnt/discimage -d -f > /dev/null 2>&1 # not working
      (mount -o loop "$file" /mnt/discimage || mount -o loop,offset=307200 "$file" /mnt/discimage) && \
        echo "/mnt/discimage" > /tmp/mp_current_path && echo "menu show" > $mp_fifo || rmdir /mnt/discimage
    elif `echo $ext | grep -iq ifo` ; then
      play_dvd "$file"
    elif `grep -iq "^$ext\$" $filter_file`; then
      if [ "$key" = "p" ]; then
        playdir "$file"
      elif [ "$key" = "l" ]; then
        playdir "$file"
      else
        echo -e "menu hide\nloadfile \"$escfile\" $append" > $mp_fifo
      fi
    elif `grep -iq "^$ext\$" $filter_playlist`; then
      echo -e "menu hide\nloadlist \"$escfile\" $append" > $mp_fifo
    elif `grep -iq "^$ext\$" $filter_image`; then
      if [ "$key" = "p" ]; then
        view_img -a "$file"
      elif [ "$key" = "l" ]; then
        view_img -r "$file"
      else
        view_img "$file"
      fi
    else
      # Extension isn't supported in our extension file but might be
      # playable as well, let's MPlayer figure it out ...
      echo -e "menu hide\nloadfile \"$escfile\" $append" > $mp_fifo
    fi
  else
    # File do not have extension, try to play it aswell ...
    echo -e "menu hide\nloadfile \"$escfile\" $append" > $mp_fifo
  fi
fi
