#!/usr/bin/env ruby

########################################
# Main
########################################

require "webrick"

# Color
BOLD  = "\x1b[1;30m"
RED   = "\x1b[0;35m"
CLEAR = "\x1b[0m"

http_config = {
  :Port          => 80,
  :RequestCallback => lambda {|req, res|
    puts req.header.map{|k, v|
      "#{BOLD}#{k}#{CLEAR}: #{RED}#{v.join(" ")}#{CLEAR}"
    }.join("\n")
    puts "\n"
  }
}

server = WEBrick::HTTPServer.new(http_config)

# /favicon.ico
server.mount("/favicon.ico", WEBrick::HTTPServlet::FileHandler, "#{__dir__}/../favicon.ico")

# /
server.mount_proc('/', Proc.new{|req, res|
  host = req.header["host"].first

  case host
  when "intra.example" then
    res.content_type = "text/html"
    res.body = File.open("./intra.html").read
  when "sns.example" then
    res.content_type = "text/html"
    res.body = File.open("./sns.html").read
  when "attack.example" then
    res.content_type = "text/html"
    res.body = File.open("./attack.html").read
  end
})

# /script.js
server.mount_proc('/script.js', Proc.new{|req, res|
  res.content_type = "application/javascript"
  res.body = <<-EOS
    console.log('hello')
  EOS
})

# /data.js
server.mount_proc('/data.js', Proc.new{|req, res|
  res.content_type = "application/javascript"
  res.body = <<-EOS
    const data = {
      username: "Jxck",
      email: "jxck@mail.example"
    }
  EOS
})

# /callback.js
server.mount_proc('/callback.js', Proc.new{|req, res|
  res.content_type = "application/javascript"
  res.body = <<-EOS
    callback({
      username: "Jxck",
      email: "jxck@mail.example"
    })
  EOS
})

Signal.trap("INT") { server.shutdown }
server.start
