# -*- encoding: utf-8

import os
import shutil
import subprocess
import sys

import click

from . import Site


@click.group()
def cli():
    pass


@cli.command('build', help='(re)build the HTML for the website')
def build():
    """
    Take the content folder and build it.
    """
    site = Site.from_folder('content')
    site.build()


@cli.command('clean', help='remove the generated HTML')
def clean():
    """
    Delete the output folder, if it exists.
    """
    try:
        shutil.rmtree('output')
    except FileNotFoundError:
        pass


@cli.command('serve', help='serve the generated website on a local port')
def serve():
    """
    Start a server on port 8900.
    """
    site = Site.from_folder('content')
    site.build()

    os.chdir('output')
    if shutil.which('docker'):
        # TODO: Don't error if the container is already running
        # TODO: Let the user choose what port to use
        subprocess.check_call(
            ['docker', 'run', '-d', '-p', '8900:80',
             '-v', '%s:/usr/local/apache2/htdocs' % os.path.abspath(os.curdir),
             'httpd'],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE
        )
    else:
        # TODO: Add support for a server with http.server
        print('Running the local web server requires Docker')
        sys.exit(1)
    print('Web server runnning on http://localhost:8900/')


@cli.command('publish', help='build the HTML for publication')
def publish():
    """
    The ``build`` command won't clean up pages or links that no longer exist.
    This command builds a fresh copy of the site, free of dead links.
    """
    for f in os.listdir('output'):
        path = os.path.join('output', f)
        if os.path.isdir(path):
            shutil.rmtree(path)
        else:
            os.unlink(path)

    site = Site.from_folder('content')
    site.build()

@@ -629,60 +629,192 @@
 t')%0A
-def serve():%0A    %22%22%22%0A    Start a server on port 8900
+@click.option('--port', default=9000, help='port for the web server',%0A              type=click.IntRange(1024, 65535))%0Adef serve(port):%0A    %22%22%22%0A    Start a local web server for the site
 .%0A  
@@ -879,39 +879,62 @@
 d()%0A
-%0A
     o
-s.chdir('output')
+ut_path = os.path.abspath(site.out_path)%0A
 %0A    if 
 shut
@@ -929,16 +929,20 @@
 %0A    if 
+not 
 shutil.w
@@ -969,157 +969,181 @@
     
-# TODO: Don't error if the container is already running%0A        # TODO: Let the user choose what port to use%0A        subprocess.check_call(%0A 
+sys.exit('Unable to find Docker; please ensure Docker is installed '%0A                 'and in the PATH.')%0A%0A    cmd = %5B%0A        # Run the container in the background%0A
         
    %5B
@@ -1142,12 +1142,8 @@
     
-   %5B
 'doc
@@ -1161,34 +1161,162 @@
 , '-
-d', '-p', '8900:80',%0A     
+-detach',%0A%0A        # Share the container port with the host%0A        '--publish', '%25d:80' %25 port,%0A%0A        # Share the output directory into the container%0A
     
@@ -1321,17 +1321,23 @@
       '-
+-
 v
+olume
 ', '%25s:/
@@ -1369,289 +1369,372 @@
  %25 o
-s.
+ut_
 path
-.abspath(os.curdir),%0A             'httpd'%5D,%0A            stdout=subprocess.PIPE,%0A            stderr=subprocess.PIPE%0A        )%0A    else:%0A        # TODO: Add support for a server with http.server%0A        print('Running the local web server requires Docker')%0A        sys.exit(1
+,%0A%0A        # Use the Apache container%0A        'httpd'%0A    %5D%0A    try:%0A        subprocess.check_call(%0A            cmd,%0A            stdout=subprocess.PIPE,%0A            stderr=subprocess.PIPE%0A        )%0A    except subprocess.CalledProcessError:%0A        sys.exit('Error starting the container - is a container already '%0A                 'running on this port?'
 )%0A
+%0A
     
@@ -1755,17 +1755,16 @@
 ver runn
-n
 ing on h
@@ -1783,14 +1783,19 @@
 ost:
-8900/'
+%25d/' %25 port
 )%0A%0A%0A

Allow the user to choose the port to serve on