#!/usr/bin/python
# -*- coding: utf-8 -*-

# Copyright © 2012 Martin Ueding <dev@martin-ueding.de>

# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.

"""
:author: Martin Ueding
:contact: dev@martin-ueding.de
:license: MIT

Creates backups from FTP servers and MySQL databases.

config file
===========

One of the entries in ``~/.config/syncscripts/servers.yaml`` can have the
following fields:

``name``
    Name of the backup.
``backupdir``
    Where the backup has to go. ``os.path.expanduser()`` is called upon this
    value.
``server``
    URL to the FTP server. Should have a trailing slash.
``subfolder``
    (optional) If only a part of the FTP has to be copied. Should have a
    trailing slash.
``dump``
    (optional) HTTP URL to the MySQL dump script.
``dump-user``
    (optional) HTTP username for the dump script.
``dump-password``
    (optional) HTTP password for the dump script.

The user and password for each server should either be in the ``server`` string
as ``ftp://user:pass@server/`` or in your ``~/.netrc``.

A part of the YAML config file could look like this:

.. code:: yaml

    -
      name: "Server Name"
      backupdir: "~/Backup"
      server: "ftp://www.example.com/"
      subfolder: "project-X"
      dump: "http://www.example.com/project-X/dump.php"
      dump-user: "user"
      dump-password: "secret"
"""

import argparse
import datetime
import os.path
import subprocess
import tempfile
import yaml

import webserverbackup

__docformat__ = "restructuredtext en"

def main():
    options = _parse_args()

    servers = load_servers(os.path.expanduser("~/.config/syncscripts/servers.yaml"))

    for server in servers:
        try:
            webserverbackup.backup_server(server)
        except subprocess.CalledProcessError as e:
            print e
        else:
            webserverbackup.update_status(server)

def update_status(server):
    """
    Update the backup-status entry.
    """
    subprocess.check_call(["backup-status", "update", server["name"]])

def load_servers(serverfile):
    """
    Loads the server data.

    :return: Server data.
    """
    with open(serverfile) as stream:
        data = yaml.load(stream)

    return data

def _parse_args():
    """
    Parses the command line arguments.

    :return: Namespace with arguments.
    :rtype: Namespace
    """
    parser = argparse.ArgumentParser(description="Creates full backups of multiple FTP servers.")
    #parser.add_argument("args", metavar="N", type=str, nargs="*", help="Positional arguments.")
    #parser.add_argument("", dest="", type="", default=, help=)
    #parser.add_argument("--version", action="version", version="<the version>")

    return parser.parse_args()

if __name__ == "__main__":
    main()
