#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2010 Eric Allen
#
# Author: Eric Allen <eric@hackerengineer.net>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 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; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

import dripbox
import re
import logging
import argparse
import sys
import os
import getpass
import subprocess

LOG_FORMAT = "%(asctime)s - %(levelname)s - %(message)s"
REMOTE_MATCH = re.compile("(.+@)?(.+):(.+)").match

logging.basicConfig(level=logging.INFO)
# parse arguments
parser = argparse.ArgumentParser(
        description='Automatically sync local files to remote')
parser.add_argument('-p', '--remote-port',
        type=int, help="SSH port on remote system")
parser.add_argument('remote', nargs=1, metavar="USER@HOST:PATH")
parser.add_argument('-s', '--sync', action="store_true", default=False,
    help="Synchronize local to remote using rsync at start")
parser.add_argument('-f', '--force', action="store_true", default=False,
    help="Force dripbox to start even with a dirty remote")
args = parser.parse_args()


def parse_remote(remote):
    username, host, remote_root = REMOTE_MATCH(remote).groups()
    if username:
        username = username.rstrip('@')
    else:
        username = getpass.getuser()

    return dict(username=username, host=host, remote_path=remote_root)

launch_args = parse_remote(args.remote[0])
launch_args['port'] = args.remote_port

port = args.remote_port or 22
if args.sync:
    command = ["rsync", "--delete", "-rltvze", "ssh -p%s" % port, "--exclude",
        ".git", ".", args.remote[0]]
    subprocess.check_call(command)
else:
    diff = subprocess.Popen(
            ["rsync", "--delete", "-crnltvze", "ssh -p%s" % port, "--exclude",
                ".git", ".", args.remote[0]],
            stdout=subprocess.PIPE)
    output, _ = diff.communicate()
    for line in output.split("\n"):
        if line == "":
            pass
        elif line == "sending incremental file list":
            pass
        elif re.match("sent \d+ bytes +received \d+ bytes  [0-9\.]+ bytes/sec", line):
            pass
        elif re.search("total size is \d+ +speedup is [0-9\.]", line):
            pass
        else:
            print "WARNING: The remote tree is out of sync with the local tree. This is a dangerous situation."
            if not args.force:
                print "Run dripbox with -f if you know what you're doing and want to run dripbox anyway"
                print "We recommend you use --sync instead."
                raise SystemExit(1)
            break

dripbox.launch(**launch_args)

print("Hit ENTER to quit")
raw_input()
sys.exit(0)
