# Source code of the Ubuntu-it website
# Copyright (C) 2015-2016  Pietro Albini <pietroalbini@ubuntu.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; witout even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import os
import sys

import click
import subprocess

import uitwww
from uitwww import utils


@click.group()
def cli():
    """ Ubuntu-it website's command line utility """
    pass


@cli.command("run")
@click.argument("data")
@click.option("-g", "--gunicorn-config", default=None, help="Path to a"
              "gunicorn config file")
@click.option("-p", "--port", default=8000, help="Bind that port")
@click.option("--public", help="Make available to the public", is_flag=True)
@click.option("-w", "--workers", help="Number of workers to start", default=3)
@click.option("-d", "--debug", help="Enable debug mode", is_flag=True)
def run(data, gunicorn_config, port, public, workers, debug):
    """Run the application"""
    # Create the application instance
    src_directory = os.path.dirname(os.path.abspath(__file__))

    app = uitwww.create_app(data)
    app.wsgi_app = utils.ReverseProxied(app.wsgi_app)

    host = "127.0.0.1"
    if public:
        host = "0.0.0.0"

    # In debug mode, run the flask builtin webserver
    if debug:
        extra_files = [
            os.path.join(src_directory, "data/navbar.yml"),
            os.path.join(src_directory, "data/permissions.yml"),
            os.path.join(src_directory, "data/redirects.yml"),
            os.path.join(src_directory, "data/downloads.toml"),
        ]

        app.run(debug=True, port=port, host=host, extra_files=extra_files)
    # Else run the application with gunicorn
    else:
        options = {
            "bind": host+":"+str(port),
            "workers": workers,
            "accesslog": "-",
            "errorlog": "-",
        }
        server = utils.GunicornInstance(gunicorn_config, options)
        server.app = app

        try:
            server.run()
        except SystemExit:
            pass


@cli.command("init")
@click.argument("data")
def init(data):
    """Initialize the data directory"""
    print("Initializing data directory:", data)
    data_path = os.path.expanduser(os.path.abspath(data))
    uitwww.init_data_directory(data_path)


@cli.command("build_scss")
def build_scss():
    """Build the scss file"""
    base_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')
    scss_file = open('%s/assets/scss/www.scss' % base_dir, 'rb')
    css_file = open('%s/uitwww/static/website.css' % base_dir, 'wb')
    subprocess.run(
        [sys.executable, '-mscss'],
        stdin=scss_file,
        stdout=css_file,
        check=True,
    )
    css_file.flush()
    scss_file.close()
    css_file.close()
