class Admin::BoxController < ApplicationController
  include ActionController::Live
  include ReverseProxy::Controller
  SocketFile = "#{Rails.root}/tmp/box.sock"
  Binary = File.expand_path("../../../../bin/box", __FILE__)
  CSSFile = File.expand_path("../../../../white-on-black.css", __FILE__)
  skip_before_action :verify_authenticity_token
  before_action :check_login

  def index
    is_not_open = `fuser #{SocketFile}`.gsub(/\n/, '').empty?
    if !File.exists?(SocketFile) || `ss -elx | grep -w "$(stat -c 'ino:%i dev:0/%d' '#{SocketFile}')"`.blank?
      Thread.new do
        `#{Binary} --unixdomain-only #{SocketFile}:$USER:$USER:0666 --disable-ssl --debug  --css #{CSSFile}`
      end
      sleep 3
    end
    reverse_proxy "unix://#{SocketFile}", path: '/' do |config|
    end
  end
  def show
    path = request.env['ORIGINAL_FULLPATH'].gsub(/.*\/admin\/box/, "")
    puts ['path', path]
    reverse_proxy "unix://#{SocketFile}", path: path do |config|
    end
  end

private
  def check_login
    user = current_user
    if user.nil? || !user.is_admin?
      return render :file => "#{Rails.root}/app/views/errors/404.html", :layout => false, :status => :not_found, :formats => [:html] 
    end
  end
end
