#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
#
# Copyright (c) 2014, 2015, 2016 Samsung Electronics.Co.Ltd.
#
# 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; version 2 of the License
#
# 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.
#
import sys
import os
import re
import errno
import subprocess

import shutil, tempfile, atexit

sys.path.insert(1, os.path.join(sys.path[0], '..'))

from common.buildtrigger import trigger_info

def execute_shell(cmd, progress=False):
    print "[INFO] command : %s" % cmd
    proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    if progress:
        line_iterator = iter(proc.stdout.readline, b"")
        for line in line_iterator:
            print "    %s" % line[:-1]
    out, err = proc.communicate()
    if cmd.startswith("rsync"):
        if err:
            print "stderr: %s" % err
            return 'err'

    if err:
        print "stderr: %s" % err
        return None

    o = out.strip().split('\n')
    print "o: %s" % o
    if len(o) == 1:
        if o[0] == '':
            return None
    return o

def main():

    print '---[JOB STARTED]-------------------------'

    content = trigger_info(os.getenv("TRIGGER_INFO"))

    if os.getenv("TRBS_SYNC_AWS_ENABLED", "0") == "0":
	return

    if 'download_url' in content:
        repo_path = content['download_url'].replace(os.getenv('URL_PUBLIC_REPO_BASE'),
                                                    os.getenv('TRBS_PATH_REPO_BASE'))
    if 'remove_path' in content:
        repo_path = content['remove_path']
    if 'repo_path' in content:
        repo_path = os.path.join(os.getenv('TRBS_PATH_REPO_BASE'),
                                 content['repo_path'])

    sync_aws_dest_base = '%s:%s' %(os.getenv('TRBS_SYNC_AWS_DEST_BASE'), repo_path)
    cmd = 'rsync --compress --stats --archive --recursive --hard-links --delete --verbose --exclude="source" %s/ %s/' \
             % (repo_path, sync_aws_dest_base)
    print "rsync command: %s" % cmd
    if execute_shell(cmd, progress=True) == 'err':
        cmd = 'rsync --compress --stats --archive --recursive --hard-links --delete --verbose --exclude="source" %s/ %s/' \
             % (os.path.dirname(repo_path), os.path.dirname(sync_aws_dest_base))
        print "rsync command: %s" % cmd
        if execute_shell(cmd, progress=True) == 'err':
            raise Exception('[Error] rsync failed.')

if __name__ == '__main__':
    sys.exit(main())
