#!/bin/sh

test -d /dev/browser || {

  move_root_to_9pfs(){
    test -d /mnt/run || mkdir /mnt/run # for javascript<->unix pids
    test -d /mnt/root && return 0
    mv /root /mnt/.
    ln -fs /mnt/root /root
  }

  setup_clipboard(){
    test -d /mnt/clipboard || {
      mkdir /mnt/clipboard
      echo "files appear here when dragdropping- or copy/pasting a file into the 3D scene (minimize in non-immersive mode)" > /mnt/clipboard/README.md
    }
  }

  setup_links(){
    ln -fs /etc/motd ~/.motd 
    ln -fs /mnt/profile.browser ~/.profile.browser
    chmod +x ~/.profile.js
  }

  setup_browser_dev(){
    mkdir -p /mnt/dev/browser 
    touch /mnt/dev/browser/js
    touch /mnt/dev/browser/html
    touch /mnt/dev/browser/console
    ln -fs /mnt/dev/browser /dev/browser
  }

  setup_network(){
    test -n "$BROWSER" || return 0
    #mount -a
    udhcpc 1>>/var/log/network.log 2>>/var/log/network.log & 
    echo 0 > /proc/sys/kernel/printk
  }

  setup_overlayfs(){
    test -f /mnt/overlayfs.zip && unzip /mnt/overlayfs.zip -d /
  }

  setup_incoming_cmds(){
    # listen for shell cmds passed to v86 from browser 
    # (via isoterminal.exec(...)) 
    stty raw < /dev/ttyS1
    mkfifo /var/run/ttyS1
    cat /dev/ttyS1 > /var/run/ttyS1 &
    /bin/sh < /var/run/ttyS1
  }

  setup_listen_homedir(){
    sleep 4
    /root/bin/watchfs &
  }

  setup_mounts(){
    mkdir /mnt/helloworld
    fusescript /root/fs/helloworld /mnt/helloworld
  }

  modprobe fuse # load fuse
  move_root_to_9pfs
  setup_browser_dev
  setup_clipboard
  setup_links
  setup_network
  setup_overlayfs
  setup_listen_homedir &
  setup_incoming_cmds &
  setup_mounts
}