#!/usr/bin/env node

const http = require('http')
const url = require('url')
const path = require('path')
const fs = require('fs')
const exec = require('child_process').execSync

const inst = require('commander')
const open = require('open')
const mime = require('mime')
const colors = require('colors')

const etc = require('../lib/etc')
var config = require('../lib/config')

inst
  .option('-p, --port <port>', 'The port on which your site will be available')
  .option('-w, --watch', 'Rebuild site if files change')
  .parse(process.argv)

if (inst.port) {
  config.port = inst.port
}

if (!etc.isSite()) {
  console.error('No site in here!'.red)
  process.exit(1)
}

if (!etc.exists(config.outputDir)) {
  try {
    exec('cory build', {stdio: [0, 1]})
  } catch (err) {
    console.error(err)
    process.exit(1)
  }
}

function respond(status, message, type, encoding) {
  var request = this

  request.writeHead(status, {'Content-Type': type || 'text/plain'})
  request.write(message || 'Not Found', encoding || 'utf8')
  request.end()
}

http.ServerResponse.prototype.send = respond

const server = http.createServer(function (request, response) {

  const uri = url.parse(request.url).pathname
  var filename = path.join(config.outputDir, uri)

  try {
    const stats = fs.statSync(filename)
  } catch (err) {
    return response.send(404)
  }

  if (stats.isDirectory()) {
    filename += 'index.html'
  }

  if (!fs.statSync(filename).isFile()) {
    return response.send(404)
  }

  const type = mime.lookup(filename)
  const encoding = type !== 'text/html' && 'binary'

  fs.readFile(filename, 'binary', function(err, file) {
    if (err) {
      return response.send(500, err)
    }

    response.send(200, file, type, encoding)
  })

})

const subPort = parseInt(config.port) - 1

server.listen(inst.watch ? subPort : config.port, function () {
  const port = this.address().port
  const url = 'http://localhost:' + port

  if (inst.watch) {
    const browserSync = require('browser-sync').create()

    browserSync.init({
      proxy: 'http://localhost:' + subPort,
      ui: false,
      port: config.port,
      notify: false,
      logPrefix: 'cory',
      watchOptions: {
        ignored: /dist|.DS_Store|.git/
      },
      files: [{
        match: [process.cwd()],
        fn: require('../lib/watch')
      }]
    })

    require('../lib/watch')(browserSync)

    process.on('SIGINT', () => {
      browserSync.exit()
      process.exit(0)
    })
  } else {
    console.log('Your site is running at ' + url)
    open(url)
  }
})

@@ -834,16 +834,17 @@
  respond
+ 
 (status,
@@ -1090,49 +1090,27 @@
 nd%0A%0A
-const server = http.createServer(function
+function middleware
  (re
@@ -1128,17 +1128,16 @@
 onse) %7B%0A
-%0A
   const 
@@ -1724,199 +1724,11 @@
  %7D)%0A
-%0A%7D)%0A%0Aconst subPort = parseInt(config.port) - 1%0A%0Aserver.listen(inst.watch ? subPort : config.port, function () %7B%0A  const port = this.address().port%0A  const url = 'http://localhost:' + port%0A%0A  
+%7D%0A%0A
 if (
@@ -1737,26 +1737,24 @@
 st.watch) %7B%0A
-  
   const brow
@@ -1797,18 +1797,16 @@
 eate()%0A%0A
-  
   browse
@@ -1826,54 +1826,51 @@
     
-  proxy: 'http://localhost:' + subPort
+server: %7B%0A      baseDir: 'dist'%0A    %7D
 ,%0A    
- 
- 
 ui: 
@@ -1872,26 +1872,24 @@
  ui: false,%0A
-  
     port: co
@@ -1903,18 +1903,16 @@
 rt,%0A    
- 
- 
 notify: 
@@ -1918,18 +1918,16 @@
  false,%0A
-  
     logP
@@ -1945,18 +1945,16 @@
 y',%0A    
- 
- 
 watchOpt
@@ -1957,26 +1957,24 @@
 hOptions: %7B%0A
-  
       ignore
@@ -2002,23 +2002,19 @@
 it/%0A    
-  
 %7D,%0A
-  
     file
@@ -2025,18 +2025,16 @@
 %7B%0A      
- 
- 
 match: %5B
@@ -2049,18 +2049,16 @@
 cwd()%5D,%0A
-  
       fn
@@ -2091,65 +2091,17 @@
     
- 
- 
 %7D%5D%0A  
- 
- 
 %7D)%0A%0A
-    require('../lib/watch')(browserSync)%0A%0A  
   pr
@@ -2131,18 +2131,16 @@
 %3E %7B%0A    
-  
 browserS
@@ -2154,18 +2154,16 @@
 t()%0A    
- 
- 
 process.
@@ -2176,23 +2176,191 @@
 )%0A  
-  %7D
+%7D)%0A%7D else %7B%0A  const server = http.createServer(middleware
 )%0A
+%0A
   
-%7D else %7B
+server.listen(config.port, function () %7B%0A    const port = this.address().port%0A    const url = 'http://localhost:' + port%0A
 %0A   
@@ -2427,8 +2427,8 @@
 %0A  %7D
+)
 %0A%7D
-)
 %0A

Use BS' built-in server for development