#!/usr/bin/python
#
# Project Chost
#
# Copyright IBM, Corp. 2014
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA  02110-1301  USA

# This module contains functions that the manipulate
# and configure the Nginx proxy.

import os
import pwd
import subprocess
from string import Template

from config import paths


def _create_ssh_config():

    sys_conf_dir = paths.sys_conf_dir
    # No certificates specified by the user

    # Read template file and create a new config file
    # with the specified parameters.
    with open(os.path.join(sys_conf_dir, "shellinaboxd.in")) as template:
        data = template.read()
    # Write file to be used for nginx.
    config_file = open(os.path.join(sys_conf_dir, "shellinaboxd"), "w")
    config_file.write(data)
    config_file.close()


def start_webssh(options):
    """Start nginx reverse proxy."""
    _create_ssh_config()
    cmd = ['systemtcl start shellinaboxd']
    subprocess.call(cmd)


def terminate_webssh():
    """Stop nginx process."""
    term_cmd = ['systemtcl stop shellinaboxd']
    subprocess.call(term_cmd)
