#!/bin/sh
# virtual file interface for THREE 

STATE=/run/THREE
LOG=~/.fuse.log

update(){
  js '
  
    let fuse_dir  = ()     => '16877 2 0 0 4096 8'
    let fuse_file = (size) => `33188 1 0 0 ${size||1} 1`

    function traverseScene(object, path = '/', result = '') {
      const objectName = object.name? object.name : object.id;
      result += `${path}${objectName} ${fuse_dir()}\n`;
      result += `${path}${objectName}/position ${fuse_dir()}\n`;
      result += `${path}${objectName}/position/x ${fuse_file()}\n`;
      result += `${path}${objectName}/position/y ${fuse_file()}\n`;
      result += `${path}${objectName}/position/z ${fuse_file()}\n`;   
      result += `${path}${objectName}/rotation ${fuse_dir()}\n`;
      result += `${path}${objectName}/rotation/x ${fuse_file()}\n`;
      result += `${path}${objectName}/rotation/y ${fuse_file()}\n`;
      result += `${path}${objectName}/rotation/z ${fuse_file()}\n`;   
      if( object.userData ){
        result += `${path}${objectName}/userData 1 1 1 1\n`;
        for( let k in object.userData )
           result += `${path}${objectName}/userData/${k} 1 1 1 1\n`;  
      }
      object.children.forEach(child => {
        result = traverseScene(child, `${path}${objectName}/`, result);
      });
      return result;
    }
    return traverseScene( document.querySelector('a-scene').object3D );
  ' > $STATE
}

readdir(){ # print first column [filename] from header
  test -f $STATE || update
  awk '/^#\'$1'/ { 
    gsub("^#'$1'[/]?","",$1); # strip dirname
    gsub("\\/.*","",$1);      # strip subdirs/files
    if( $1 ) print $1
  }' $STATE | uniq 
}

getattr(){ # print column 2 till 7 from header
  awk '$1 == "#'$1'" { print $2" "$3" "$4" "$5" "$6" "$7 }' $STATE
  grep -qE '#$1' $0 || return 2 # FUSE expects -NOENT if file does not exist
}

read(){ # print everything (data) after 7th column
  awk '$1 == "#'$1'" { $1=$2=$3=$4=$5=$6=$7=""; sub(/^ +/, ""); print $0 }' $0
}

getxattr(){ # print xattr value from commentheader
  awk '$1 == "#xattr:'$1'" && $2 == "'$2'" { print $3 }' $STATE
}

setxattr(){ # save xattr value from commentheader
  file=$1 ; key=$2 ; shift; shift
  sed -i "s/^#xattr:\\$key .*/#xattr:\\$key $*" $STATE || echo "#xattr:$file $key $*" >> $0
}

listxattr(){ # list xattr keys
  awk '$1 == "#xattr:'$1'" { printf("%s\0",$2) }' $STATE
}

echo "> $0 $*" >> $LOG
"$@" | tee -a $LOG