#!/usr/bin/env python
#
# 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 script is used to delete local gerrit project when remote is deleted"""

import os
import shutil
import sys

from common.gerrit import Gerrit

def find_local_projects(work_dir):
    """Find gerrit projects in local git dirs"""

    projects = []

    for path in os.listdir(work_dir):
        abs_path = os.path.abspath(os.path.join(work_dir, path))
        if os.path.isdir(abs_path):
            if os.path.exists(os.path.join(abs_path, '.git')):
                projects.append(abs_path)
            else:
                projects.extend(find_local_projects(abs_path))

    return projects

def main():
    """The main body"""

    for env in ('GIT_CACHE_DIR', 'GERRIT_HOSTNAME', 'GERRIT_USERNAME'):
        if env not in os.environ:
            print >> sys.stderr, 'Environment variable %s is not defined' % env
            return -1

    work_dir = os.getenv('GIT_CACHE_DIR')

    local_projects = set([project[len(work_dir)+1:] for \
            project in find_local_projects(work_dir)])

    remote_projects = set(Gerrit(os.getenv('GERRIT_HOSTNAME'), \
            os.getenv('GERRIT_USERNAME')).ls_projects())

    diff_projects = local_projects.difference(remote_projects)
    # debug information
    print 'Differences are: %s' % diff_projects

    for project in diff_projects:
        shutil.rmtree(os.path.join(work_dir, project))
        print '%s is deleted ...' % project

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