#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# https://docs.python.org/3.5/howto/pyporting.html#prevent-compatibility-regressions
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
import signal
import subprocess
import sys

import daemon
from lockfile.pidlockfile import PIDLockFile

stdout = open('{{ consul_daemon_log_dir }}/stdout.log', mode='a+')
stderr = open('{{ consul_daemon_log_dir }}/stderr.log', mode='a+')
pidfile = PIDLockFile('{{ consul_daemon_pid_dir }}/consul.pid')


def do_start(commands):
    with daemon.DaemonContext(stdout=stdout, stderr=stderr, pidfile=pidfile):
        child_process = subprocess.Popen(commands)
        child_process.communicate()
        child_process.terminate()


def do_stop():
    os.killpg(os.getpgid(pidfile.read_pid()), signal.SIGTERM)


def do_restart():
    do_stop()
    do_start()

if __name__ == '__main__':
    base_command = '{{ consul_script_remote_dir }}/services.sh'
    if sys.argv[1] == 'start':
        do_start([base_command] + sys.argv[2:])
    elif sys.argv[1] == 'stop':
        do_stop()
    elif sys.argv[1] == 'restart':
        do_restart()
    else:
        do_start([base_command] + sys.argv[2:])

@@ -236,16 +236,29 @@
 nction%0A%0A
+import click%0A
 import o
@@ -566,32 +566,157 @@
 ')%0A%0A
-%0Adef do_start(commands):
+context_settings = dict(help_option_names=%5B'-h', '--help'%5D)%0A%0A%0Adef do_start(mode):%0A    commands = %5B'%7B%7B consul_script_remote_dir %7D%7D/services.sh', mode%5D
 %0A   
@@ -788,16 +788,27 @@
 pidfile)
+ as context
 :%0A      
@@ -1007,182 +1007,333 @@
 )%0A%0A%0A
-def do_restart():%0A    do_stop()%0A    do_start()%0A%0Aif __name__ == '__main__':
+@click.group(context_settings=context_settings)%0Adef consul_cli():%0A    '''%0A    CLI to manage Consul daemon processes.%0A    '''
 %0A    
-base_command = '%7B%7B consul_script_remote_dir %7D%7D/services.sh'%0A    if sys.argv%5B1%5D == 'start':
+pass%0A%0A%0A@consul_cli.command()%0A@click.argument('mode', type=click.Choice(%5B'dev', 'client', 'server'%5D))%0Adef start(mode):%0A    '''%0A    Start Consul daemon processes on MODE(dev/client/server).
 %0A    
+'''%0A
     
@@ -1345,75 +1345,100 @@
 art(
-%5Bbase_command%5D + sys.argv%5B2:%5D)%0A    elif sys.argv%5B1%5D == 'stop':
+mode)%0A%0A%0A@consul_cli.command()%0Adef stop():%0A    '''%0A    Stop Consul daemon processes.
 %0A    
+'''%0A
     
@@ -1451,118 +1451,277 @@
 p()%0A
-    elif sys.argv%5B1%5D == 'restart':%0A        do_restart()%0A    else:%0A        do_start(%5Bbase_command%5D + sys.argv%5B2:%5D
+%0A%0A@consul_cli.command()%0A@click.argument('mode', type=click.Choice(%5B'dev', 'client', 'server'%5D))%0Adef restart(mode):%0A    '''%0A    Restart Consul daemon processes on MODE(dev/client/server).%0A    '''%0A    do_stop()%0A    do_start(mode)%0A%0Aif __name__ == '__main__':%0A    consul_cli(
 )%0A

Refactor daemon script with subcommands.