#!/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 os
import sys
import ast
from datetime import datetime

from common.buildservice import BuildService
from common.gerrit import GerritEnv
from common.mapping import get_ref_map

class LocalError(Exception):
    """Local error exception."""
    pass

def secure_tag_time_format(tag_info):
    _YYYYmmdd = tag_info.split('.')[0]
    _HHMMSS = tag_info.split('.')[-1]

    _YYYY = int(_YYYYmmdd) / 10000
    _mm = int(_YYYYmmdd) / 100 % 100
    _dd = int(_YYYYmmdd) % 100
    _HH = int(_HHMMSS) / 10000
    _MM = int(_HHMMSS) / 100 % 100
    _SS = int(_HHMMSS) % 100

    if _mm > 12: _mm = 12
    if _dd > 31: _dd = 31
    if _HH > 23: _HH = 23
    if _MM > 59: _MM = 59
    if _SS > 59: _SS = 59

    return '%04d%02d%02d.%02d%02d%02d' % (_YYYY, _mm, _dd, _HH, _MM, _SS)

def main():
    """
    Auto purge project to obs
    """

    obs_api = os.getenv("OBS_API_URL")
    obs_user = os.getenv("OBS_API_USERNAME")
    obs_passwd = os.getenv("OBS_API_PASSWD")

    # get list of ref projects from git-ref-mapping
    obs_ref_prjs = get_ref_map('/',None)
    #print 'obs_ref_prjs = %s' %obs_ref_prjs

    build = BuildService(obs_api, obs_user, obs_passwd)

    all_prj_list = [ obj for obj in build.get_package_list("") \
                 if not obj.find("Tizen:") == -1 \
                 and not obj.find(":ref:") == -1 \
                 and obj.find(":Base:") == -1 ]

    # Limit purge project , remove the project list
    prj_list = []
    if os.getenv("REF_LIMIT_PURGE_PRJ_CNT"):
        for x in ast.literal_eval(os.getenv("REF_ACTIVE_PRJS")):
            count = 0
            for obj in sorted(all_prj_list, reverse=True):
                if not obj.find(x['project'] + ":ref:") == -1:
                    if count >= int(os.getenv("REF_LIMIT_PURGE_PRJ_CNT")):
                        prj_list.append(obj)
                    else:
                        count = count + 1

    print "Ref project = %s"  %(prj_list)

    now_datetime = datetime.now()
    #### Purge the reference project to obs ( 14day) ####
    if os.getenv("REF_PURGE_PRJ_HOUR"):
        remove_hour = os.getenv("REF_PURGE_PRJ_HOUR")
        for prj in prj_list:
            if int(prj.split('.')[-1]) > 23:
                prj_temp = '%s.23' % ('.'.join(prj.split('.')[:-1]))
                create_datetime = datetime.strptime(prj_temp.split(':')[-1], "%Y%m%d.%H")
            else:
                create_datetime = datetime.strptime(prj.split(':')[-1], "%Y%m%d.%H")
            #print create_datetime
            post_hour = divmod((now_datetime - create_datetime).total_seconds(), 3600)[0]
            if int(post_hour) > int(remove_hour):
                cleanup = True
                for reftarget in obs_ref_prjs:
                    #print 'ref=%s prj=%s' %(reftarget['OBS_staging_project'],prj)
                    if reftarget['OBS_staging_project'] == prj:
                        cleanup = False
                        break
                if cleanup:
                    try:
                        print "%s project is remove." % prj
                        sys.stdout.flush()
                        build.cleanup(prj, "This project has expired")
                    except Exception as err:
                        print "%s project is remove error = %s" % (prj, err)
                else:
                    print "%s project is reference project. Skip remove project !!!!" % prj

    return

if __name__ == '__main__':
    try:
        sys.exit(main())
    except LocalError, err:
        print err
        sys.exit(1)

