#!/bin/bash

# sudo docker run -p 80:8080 -p 59000-59100:59000-59100/udp --cap-add SYS_ADMIN --shm-size=1gb nurdism/neko:chromium 
# sudo docker run -p 80:8080 -p 59000-59100:59000-59100/udp --shm-size=1gb nurdism/neko:firefox
# sudo docker run --network host --shm-size=1gb -it nurdism/neko:base /bin/bash

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )/.."

build_gst() {
  if [ ! -L /gst || ! -d /gst ]; then
    sudo rm -rf /gst;
    sudo mkdir -p /workspace/.build/gst
    sudo ln -s /workspace/.build/gst /gst
    sudo chown -R neko /workspace/.build
  fi
  
  #
  # build & install gstreamer 
  sudo su -c 'set -eux; \
    rm -rf /gst/local; \
    cd /gst; \
    for MODULE in \
      gstreamer \
      gst-plugins-base \
      gst-plugins-good \
    ; do \
      if [ ! -d $MODULE ]; then
        git clone git://anongit.freedesktop.org/gstreamer/$MODULE; \
      fi
      cd $MODULE; \
      git checkout 1.16; \
      case $MODULE in \
        gstreamer) GST_ARGS="--disable-gtk-doc" ;; \
        gst-plugins-base) GST_ARGS="--disable-gtk-doc --disable-x --disable-xvideo" ;; \
        gst-plugins-good) GST_ARGS="--disable-gtk-doc --disable-oss --disable-oss4 --disable-gst_v4l2" ;; \
      esac; \
      PATH=/gst/local/bin:$PATH PKG_CONFIG_PATH=/gst/local/lib/pkgconfig ./autogen.sh --prefix /gst/local $GST_ARGS; \
      make; make install; \
      cd /gst; \
    done'
}

build_base() {
  set -eux; \
    cd $DIR/server; go get -v -t -d . ; ./build; \
    cd $DIR/client; npm install; npm run build; \
    cd $DIR; sudo docker build -f .docker/files/base/Dockerfile -t nurdism/neko:base . ;
}

build_latest() {
  set -eux; \
   cd $DIR; sudo docker build -f .docker/files/$1/Dockerfile -t nurdism/neko:latest . ; 
}

build_image() {
  set -eux; \
    cd $DIR; sudo docker build -f .docker/files/$1/Dockerfile -t nurdism/neko:$1 . ; 
}

build() {
  if [ ! -d /gst/local ]; then
    build_gst
  fi

  if [ $1 != "" ]; then
    build_image $1
  else
    set -eux; \
      build_image "deps"; \
      build_image "base"; \
      build_base; \
      build_image "openbox"; \
      build_image "xfce4"; \
      build_image "jwm"; \
      build_image "firefox"; \
      build_image "chromium"; \
      build_image "tor-browser";
  fi

  sudo docker images nurdism/neko 
}

push() {
  if [ $1 != "" ]; then
    sudo docker push nurdism/neko:$1
  else
    sudo docker push nurdism/neko:deps 
    sudo docker push nurdism/neko:base 
    sudo docker push nurdism/neko:openbox 
    sudo docker push nurdism/neko:xfce4 
    sudo docker push nurdism/neko:jwm 
    sudo docker push nurdism/neko:firefox 
    sudo docker push nurdism/neko:chromium 
    sudo docker push nurdism/neko:tor-browser 
  fi
}

case $1 in
  images) build;;
  image) build $2 ;;
  push) push $2 ;;
  latest) build_latest ;;
  base) build_image "base" ;;
  deps) build_image "deps" ;;
  dev) build_image "dev" ;;
  gst) build_gst ;;
  *) build_docker ;;
esac
