#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
#
# Copyright (C) 2010, 2011, 2012, 2013, 2014 Intel, Inc.
#
#    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.
#
#    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.
#
"""
This code is called when create snapshot.
"""

import os
import sys
import shutil
import re
import subprocess

from xml.dom import minidom

from common.buildtrigger import trigger_info, trigger_next
from common.buildservice import BuildService

def main():
    """Script entry point.
    """

    print '---[JOB STARTED: buildlog ]-------------------------'

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

    gbsbuild_dic = content.get("gbsbuild_dic")
    obs_prj = content.get("project")
    if gbsbuild_dic:
        live_repo_base = os.path.join(os.getenv('PATH_LIVE_REPO_BASE'),os.getenv('GBSDBBUILD_DL_POSTFIX'))
        sync_src = os.path.join(live_repo_base,obs_prj.replace(':',':/'),
                       gbsbuild_dic['gbsbuild_tag'].split('/')[-1],'buildlogs')
    else:
        live_repo_base = os.path.join(os.getenv('PATH_LIVE_REPO_BASE'),os.getenv('GBSFULLBUILD_DL_POSTFIX'))
        sync_src = os.path.join(live_repo_base,obs_prj.replace(':',':/'),'buildlogs')

    sync_dest = os.path.join(os.getenv('PATH_REPO_BASE'),content['repo_path'],'builddata/buildlogs')

    if os.path.exists(sync_dest):
        cmd = 'rm -rf '+sync_dest
        subprocess.call(cmd, stdout=sys.stdout,stderr=sys.stderr, shell=True)
    
    # copy buildlogs from live to snapshot
    shutil.copytree(sync_src, sync_dest)

    data={}
    data['obs_project'] = obs_prj
    data['action'] = "build_dep_graph"
    data['repo_path'] = content['repo_path']
    trigger_next("make_dep_graph", data)

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