#!/bin/sh

test -d /dev/browser || {

  setup_binaries(){
    for bin in /mnt/js* /mnt/v86pipe /mnt/xrsh; do 
      chmod +x $bin
      ln -s $bin /bin/.
    done
  }

  setup_links(){
    ln -s /mnt/profile ~/.profile
    ln -s /mnt/profile.js ~/.profile.js
    ln -s /mnt/profile.browser ~/.profile.browser
    ln -s /mnt/profile.sh ~/.profile.sh
    ln -s /mnt/motd ~/.motd 
    ln -s ~/.profile.js ~/index.js
    chmod +x ~/.profile.js
  }

  setup_browser_dev(){
    mkdir -p /mnt/dev/browser
    touch /mnt/dev/browser/js
    touch /mnt/console.tty
    ln -s /mnt/dev/browser /dev/browser
    # emulator.write_file() only writes to /mnt/. :(
    # should be in /proc, but v86 gives 'no such file or dir' when creating it there
    ln -s /mnt/console.tty /dev/browser/console.tty 
    echo 1 > /dev/browser/console.tty
    touch /mnt/console    && ln -s /mnt/console /dev/browser/console
    touch /mnt/index.html && ln -s /mnt/index.html /dev/browser/index.html
    ln -s /dev/browser/index.html ~/index.html

    test -f /etc/profile && rm /etc/profile
    ln -s /mnt/profile /etc/profile
  }

  setup_hook_dirs(){ # see /mnt/hook for usage
    mkdir ~/bin
    mkdir -p ~/hook.d/alert  
    echo -e "#!/bin/sh\necho hook.d/alert/yo: yo \$*"                                   > ~/hook.d/alert/yo 
    echo -e "#!/bin/js\nstr = \"hook.d/alert/yo.js yo \"+args.slice(1).join(' ')\nalert(str)\nreturn str" > ~/hook.d/alert/yo.js
    echo -e "#!/usr/bin/env lua\nprint(\"hook.d/alert/yo.lua: yo \" .. arg[1])"         > ~/hook.d/alert/yo.lua
    echo -e "#!/usr/bin/awk -f\nBEGIN{\n\tprint \"hook.d/alert/yo.awk: yo \" ARGV[1]\n}" > ~/hook.d/alert/yo.awk
    echo -e "#!/bin/sh\necho hello \$*"                                                 > ~/bin/hello 
    chmod +x ~/bin/hello
  }

  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_binaries
  setup_browser_dev
  setup_hook_dirs
  setup_links
  setup_network

}