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

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

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 remove project
    """

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

    # prepare separate temp directory for each build
    gerrit_env = GerritEnv("PUBLIC_")
    git_cache = gerrit_env.gitcache

    # get list of ref projects from git-ref-mapping
    obs_ref_prjs = get_ref_map('/',None, \
                               gitcache=gerrit_env.gitcache, \
                               gerrit_hostname=gerrit_env.hostname, \
                               gerrit_username=gerrit_env.username, \
                               gerrit_sshport=gerrit_env.sshport
                               )
    #print 'obs_ref_prjs = %s' %obs_ref_prjs

    build = BuildService(obs_api, obs_user, obs_passwd)

    #### Remove the trbs project ( 3day )####
    remove_hour = (7 * 24)
    prj_list = [ obj for obj in build.get_package_list("") if not obj.find(":trbs:") == -1 ]
    print "trbs obs project = %s"  %(prj_list)
    now_datetime = datetime.now()

    for prj in prj_list:
        #print prj, prj.split(':')[-1]
        newtime = secure_tag_time_format(prj.split(':')[-1])
        create_datetime = datetime.strptime(newtime, "%Y%m%d.%H%M%S")
        #print create_datetime
        post_hour = divmod((now_datetime - create_datetime).total_seconds(), 3600)[0]
        if int(post_hour) > int(remove_hour):
            build.cleanup(prj, "This project has expired")
            print "%s project is remove." % prj

    #### Remove the ref obs project ( 14day) ####
    remove_hour = (21 * 24)
    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(":trbs:") == -1 \
                 and obj.find(":Base:") == -1 ]
    print "ref obs project = %s"  %(prj_list)
    now_datetime = datetime.now()
    for prj in prj_list:
        #print prj, prj.split(':')[-1]
        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:
                build.cleanup(prj, "This project has expired")
                print "%s project is remove." % prj
            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)
