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

import os
import sys
import argparse


def query_yes_no(question):
    valid = {"yes": True, "y": True, "ye": True,
             "no": False, "n": False}
    sys.stdout.write(question + ' [y/N]: ')
    choice = raw_input().lower()
    if choice == '':
        return False
    return valid.get(choice, False)

parser = argparse.ArgumentParser(description='Sync project with remote host')
parser.add_argument('--auto', action='store_true', help='Skip questions')
parser.add_argument('--host', help='remote host (default: user_name@user_name.avia.dev.yandex.net)')
parser.add_argument('--env', default='dev', help='environment')
args = parser.parse_args()
pwd = os.getcwd()

project_name = pwd.split('/')[-1]
path_from_home = '/'.join(pwd.split('/')[3:])
user_name = os.environ['USER']
deploy_path = '{user_name}@{host}:~/{path_from_home}'.format(
    user_name=user_name,
    host=args.host or '{}.avia.dev.yandex.net'.format(user_name),
    path_from_home=path_from_home
)

print 'Project: [{}]'.format(project_name)
print 'User name: [{}]'.format(user_name)

if not args.auto and not query_yes_no('Sync {}/ with {}?'.format(pwd, deploy_path)):
    sys.exit()

node_bin = 'node'
nodemon_bin = './node_modules/.bin/nodemon'
if args.env == 'launchd':
    node_bin = '/usr/local/bin/node'


rsync_flags = '-arvz --inplace --exclude-from .rsyncignore'
watch_command = 'rsync {rsync_flags} {pwd}/ {deploy_path} &'.format(rsync_flags=rsync_flags,
                                                                    pwd=pwd,
                                                                    deploy_path=deploy_path)
os.system('{node_bin} {nodemon_bin} -x "{watch_command}"'.format(
          node_bin=node_bin,
          nodemon_bin=nodemon_bin,
          watch_command=watch_command))
