# Path: fabgis/common.py
# def setup_env():
#     """Things to do regardless of whether command is local or remote.
# 
#     Todo - many of these env.fg settings should be module specific...
# 
#     """
#     if env.fg is not None:
#         fastprint('Environment already set!\n')
#         return
# 
#     fastprint('Setting environment!\n')
#     env.fg = fdict()
#     with hide('output'):
#         env.fg.user = run('whoami')
#         # Workaround for
#         env.fg.hostname = run('hostname')
#         # this which fails in docker - see
#         # https://github.com/dotcloud/docker/issues/1301
#         #env.fg.hostname = fabtools.system.get_hostname()
#         env.fg.home = os.path.join('/home/', env.fg.user)
#         env.fg.workspace = os.path.join(env.fg.home, 'dev')
#         env.fg.inasafe_git_url = 'git://github.com/AIFDR/inasafe.git'
#         env.fg.qgis_git_url = 'git://github.com/qgis/QGIS.git'
#         env.fg.kandan_git_url = 'git://github.com/kandanapp/kandan.git'
#         env.fg.gdal_svn_url = 'https://svn.osgeo.org/gdal/trunk/gdal'
#         env.fg.inasafe_checkout_alias = 'inasafe-fabric'
#         env.fg.qgis_checkout_alias = 'qgis-fabric'
#         env.fg.inasafe_code_path = os.path.join(
#             env.fg.workspace, env.fg.inasafe_checkout_alias)
#         env.fg.qgis_code_path = os.path.join(
#             env.fg.workspace, env.fg.qgis_checkout_alias)
# 
# def show_environment():
#     """For diagnostics - show any pertinent info about server."""
#     setup_env()
#     fastprint('\n-------------------------------------------------\n')
#     for key, value in env.fg.iteritems():
#         fastprint('Key: %s \t\t Value: %s\n' % (key, value))
#     fastprint('-------------------------------------------------\n')
# 
# @task
# def add_ubuntugis_ppa():
#     """Ensure we have ubuntu-gis repo."""
#     fabtools.deb.update_index(quiet=True)
#     fabtools.require.deb.package('software-properties-common')
#     fabtools.require.deb.ppa(
#         #'ppa:ubuntugis/ubuntugis-unstable', auto_yes=True)
#         'ppa:ubuntugis/ubuntugis-unstable')
# 
# Path: fabgis/utilities.py
# def replace_tokens(conf_file, tokens):
#     """Deprecated: prepare a template config file by replacing its tokens.
# 
#     :param conf_file: Either a full path to a conf file name or just the
#         file name. In the latter case, it assumes the file is then in the
#         current working directory. It the file name ends in '.templ',
#         a copy will be made and the takens replaced in the copy. Otherwise
#         the original file will be manipulated.
#     :type conf_file: str
# 
#     :param tokens: A dictionary of key-values that should be replaced
#         in the conf file.
#     :type tokens: dic
# 
#     :returns: Path to the replaced file.
#     :rtype: str
# 
#     Example tokens::
# 
#         my_tokens = {
#             'SERVERNAME': env.doc_site_name,  # Web Url e.g. foo.com
#             'WEBMASTER': 'werner@linfiniti.com',  # email of web master
#             'DOCUMENTROOT': webdir,  # Content root .e.g. /var/www
#             'SITENAME': sitename,  # Choosen name of jenkins 'root'
#         }
# 
#     .. deprecated:: You should use fabric.contrib.files.upload_template rather.
#     """
# 
#     if '.templ' == conf_file[-6:]:
#         templ_file = conf_file
#         conf_file = conf_file.replace('.templ', '')
#         sudo(
#             'cp %(templ_file)s %(conf_file)s' % {
#             'templ_file': templ_file,
#             'conf_file': conf_file})
# 
#     base_path, file_name = os.path.split(conf_file)
#     if base_path is not '':
#         # The file is not in the current working dir.
#         with cd(base_path):
#             for key, value in tokens.iteritems():
#                 sudo('sed -i.bak -r -e "s/\[%s\]/%s/g" %s' % (
#                     key, value, file_name))
#             sudo('rm %s.bak' % file_name)
#     else:
#         # filename only, not full path - assumes the current working dir is
#         # the same as where the conf file is located
#         for key, value in tokens.iteritems():
#             sudo('sed -i.bak -r -e "s/\[%s\]/%s/g" %s' % (
#                 key, value, file_name))
#             sudo('rm %s.bak' % file_name)
#     return conf_file


import os
import fabtools
from fabric.contrib.files import exists
from fabtools.postgres import create_user
from fabric.colors import red, green, blue
from fabric.api import run, cd, env, task, sudo, get, put, fastprint
from .common import setup_env, show_environment, add_ubuntugis_ppa
from .utilities import replace_tokens

@task
def setup_nightly_backups():
    """Setup nightly backups for all postgresql databases.

    The template script :file:`fabgis_resources/server_config/cron/pg_backups`
    will place the last 21 days of backups in the remote user's Dropbox
    directory and will maintain 6 months of backups in their home directory.

    .. seealso:: fabgis.dropbox for help on setting up dropbox on your server.
    """
    setup_env()
    setup_postgres_superuser(env.fg.user)
    with cd('/etc/cron.daily/'):
        if exists('pg_backups'):
            sudo('rm pg_backups')

        local_dir = os.path.dirname(__file__)
        local_file = os.path.abspath(os.path.join(
            local_dir,
            '..',
            'fabgis_resources',
            'server_config',
            'cron',
            'pg_backups.templ'))
        put(local_file,
            '/etc/cron.daily/pg_backups',
            use_sudo=True)

        my_tokens = {'USER': env.fg.user, }

# Path: fabgis/common.py
# def setup_env():
#     """Things to do regardless of whether command is local or remote.
# 
#     Todo - many of these env.fg settings should be module specific...
# 
#     """
#     if env.fg is not None:
#         fastprint('Environment already set!\n')
#         return
# 
#     fastprint('Setting environment!\n')
#     env.fg = fdict()
#     with hide('output'):
#         env.fg.user = run('whoami')
#         # Workaround for
#         env.fg.hostname = run('hostname')
#         # this which fails in docker - see
#         # https://github.com/dotcloud/docker/issues/1301
#         #env.fg.hostname = fabtools.system.get_hostname()
#         env.fg.home = os.path.join('/home/', env.fg.user)
#         env.fg.workspace = os.path.join(env.fg.home, 'dev')
#         env.fg.inasafe_git_url = 'git://github.com/AIFDR/inasafe.git'
#         env.fg.qgis_git_url = 'git://github.com/qgis/QGIS.git'
#         env.fg.kandan_git_url = 'git://github.com/kandanapp/kandan.git'
#         env.fg.gdal_svn_url = 'https://svn.osgeo.org/gdal/trunk/gdal'
#         env.fg.inasafe_checkout_alias = 'inasafe-fabric'
#         env.fg.qgis_checkout_alias = 'qgis-fabric'
#         env.fg.inasafe_code_path = os.path.join(
#             env.fg.workspace, env.fg.inasafe_checkout_alias)
#         env.fg.qgis_code_path = os.path.join(
#             env.fg.workspace, env.fg.qgis_checkout_alias)
# 
# def show_environment():
#     """For diagnostics - show any pertinent info about server."""
#     setup_env()
#     fastprint('\n-------------------------------------------------\n')
#     for key, value in env.fg.iteritems():
#         fastprint('Key: %s \t\t Value: %s\n' % (key, value))
#     fastprint('-------------------------------------------------\n')
# 
# @task
# def add_ubuntugis_ppa():
#     """Ensure we have ubuntu-gis repo."""
#     fabtools.deb.update_index(quiet=True)
#     fabtools.require.deb.package('software-properties-common')
#     fabtools.require.deb.ppa(
#         #'ppa:ubuntugis/ubuntugis-unstable', auto_yes=True)
#         'ppa:ubuntugis/ubuntugis-unstable')
# 
# Path: fabgis/utilities.py
# def replace_tokens(conf_file, tokens):
#     """Deprecated: prepare a template config file by replacing its tokens.
# 
#     :param conf_file: Either a full path to a conf file name or just the
#         file name. In the latter case, it assumes the file is then in the
#         current working directory. It the file name ends in '.templ',
#         a copy will be made and the takens replaced in the copy. Otherwise
#         the original file will be manipulated.
#     :type conf_file: str
# 
#     :param tokens: A dictionary of key-values that should be replaced
#         in the conf file.
#     :type tokens: dic
# 
#     :returns: Path to the replaced file.
#     :rtype: str
# 
#     Example tokens::
# 
#         my_tokens = {
#             'SERVERNAME': env.doc_site_name,  # Web Url e.g. foo.com
#             'WEBMASTER': 'werner@linfiniti.com',  # email of web master
#             'DOCUMENTROOT': webdir,  # Content root .e.g. /var/www
#             'SITENAME': sitename,  # Choosen name of jenkins 'root'
#         }
# 
#     .. deprecated:: You should use fabric.contrib.files.upload_template rather.
#     """
# 
#     if '.templ' == conf_file[-6:]:
#         templ_file = conf_file
#         conf_file = conf_file.replace('.templ', '')
#         sudo(
#             'cp %(templ_file)s %(conf_file)s' % {
#             'templ_file': templ_file,
#             'conf_file': conf_file})
# 
#     base_path, file_name = os.path.split(conf_file)
#     if base_path is not '':
#         # The file is not in the current working dir.
#         with cd(base_path):
#             for key, value in tokens.iteritems():
#                 sudo('sed -i.bak -r -e "s/\[%s\]/%s/g" %s' % (
#                     key, value, file_name))
#             sudo('rm %s.bak' % file_name)
#     else:
#         # filename only, not full path - assumes the current working dir is
#         # the same as where the conf file is located
#         for key, value in tokens.iteritems():
#             sudo('sed -i.bak -r -e "s/\[%s\]/%s/g" %s' % (
#                 key, value, file_name))
#             sudo('rm %s.bak' % file_name)
#     return conf_file


# Path: fabgis/postgres.py
import os
import fabtools
from fabric.contrib.files import exists
from fabtools.postgres import create_user
from fabric.colors import red, green, blue
from fabric.api import run, cd, env, task, sudo, get, put, fastprint
from .common import setup_env, show_environment, add_ubuntugis_ppa
from .utilities import replace_tokens


@task
def setup_nightly_backups():
    """Setup nightly backups for all postgresql databases.

    The template script :file:`fabgis_resources/server_config/cron/pg_backups`
    will place the last 21 days of backups in the remote user's Dropbox
    directory and will maintain 6 months of backups in their home directory.

    .. seealso:: fabgis.dropbox for help on setting up dropbox on your server.
    """
    setup_env()
    setup_postgres_superuser(env.fg.user)
    with cd('/etc/cron.daily/'):
        if exists('pg_backups'):
            sudo('rm pg_backups')

        local_dir = os.path.dirname(__file__)
        local_file = os.path.abspath(os.path.join(
            local_dir,
            '..',
            'fabgis_resources',
            'server_config',
            'cron',
            'pg_backups.templ'))
        put(local_file,
            '/etc/cron.daily/pg_backups',
            use_sudo=True)

        my_tokens = {'USER': env.fg.user, }

        replace_tokens('/etc/cron.daily/pg_backups', my_tokens)