#!/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.
#

import os
import sys
import re
import requests
from bs4 import BeautifulSoup

sys.path.insert(1, os.path.join(sys.path[0], '..'))
from common.send_mail import prepare_mail


# set default char-set endcoding to utf-8
reload(sys)
sys.setdefaultencoding('utf-8') # pylint: disable-msg=E1101

TOOLS_RELEASE_URL = "http://download.tizen.org/tools/archive/"
TOOLS_RELEASE_TITLE = '[Dev] Tizen SCM Tools Release - %s'

TOOLS_RELEASE_BODY = 'Hi, Everyone.\n\n' \
             'Tizen SCM Tools packages are released.\n' \
             '- Tizen SCM Tools : http://download.tizen.org/tools/latest-release/ ( http://download.tizen.org/tools/archive/%s/ )\n\n' \
             'For details on \'New Features & Enhancements\' and \'Bug Fixes\', please refer to Release Notes : \n' \
             '- http://download.tizen.org/tools/archive/%s/RELEASE_NOTES_GBS.txt \n' \
             '- http://download.tizen.org/tools/archive/%s/RELEASE_NOTES_MIC.txt \n\n' \
             'Best Regards.' \


TOOLS_RELEASE_FOOTER = '\n\n--------------------------------------------------------\n'\
               'Automatically generated by backend service.\n'\
               'Please DO NOT Reply!'

TOOLS_RELEASE_FILES = ["RELEASE_NOTES_GBS.txt",\
             "RELEASE_NOTES_MIC.txt",\
             "RELEASE_NOTES_REPA.txt"]

def send_mail_tool_release_message(release_id):
    """ send mail about tools release """

    #make a message
    title = TOOLS_RELEASE_TITLE % ( release_id)
    email_body = TOOLS_RELEASE_BODY % (release_id, release_id, release_id)

    msg = email_body + TOOLS_RELEASE_FOOTER

    submitter = os.getenv('TO')

    if submitter:
        prepare_mail("%s.env" % os.getenv('BUILD_TAG'), title, msg,
                     os.getenv('NOREPLY_EMAIL_SENDER'), submitter)

    print "\n\n--------------------------------------------------------\n"
    print os.getenv('NOREPLY_EMAIL_SENDER')
    print title
    print msg
    print submitter

def check_mail_send_option(option):
    #check option condition
    check_result = "TRUE"

    if len(option) < 5:
        print "Need more input data"
        return "Need more input data"

    release_id = option[2]
    destination = option[3]

    if release_id != None:
        regex = re.compile(r'^[0-9]{2}.[0-9]{2}.[0-9]{1,3}$')
        release_id_pattern = regex.search(release_id)
        print release_id, release_id_pattern
        if release_id_pattern == None:
            return "Need change value for release_id : %s " % (release_id)

    if option[3] == "staging":
        print "Jenkins destination parameter value is staging"
        return "Need change value for destination" 

    return check_result


def check_release_txt_file(option):
    #check option condition
    check_result = "TRUE"
    url = TOOLS_RELEASE_URL+option[2]
    f = requests.get(url, timeout=30)
    if f.status_code != 200:
        return ("%s url error" % (url))

    soup = BeautifulSoup(f.text, 'html.parser')

    for l in TOOLS_RELEASE_FILES:
        pattern_text = l
        result=str(soup.findAll('a', attrs={'href': re.compile(pattern_text)}))
        if pattern_text not in result:
            return (" %s version is not in %s " % (pattern_text, url))

    return check_result


def check_release_id_option(option):
    #check option condition
    check_result = "TRUE"
    url = TOOLS_RELEASE_URL

    f = requests.get(url, timeout=30)
    if f.status_code != 200:
        return ("%s url error" % (url))

    soup = BeautifulSoup(f.text, 'html.parser')
    pattern_version=option[2]
    result=str(soup.findAll('a', attrs={'href': re.compile(pattern_version)}))

    if pattern_version not in result:
        return (" %s version is not in %s " % (pattern_version, url))

    return check_result


def mail_send_condion_check(option):
    """ Check condition before send mail  """

    #check option condition
    check_result = "TRUE"

    #1) Check option
    check_result = check_mail_send_option(option)
    if check_result != "TRUE":
        return check_result
    else:
        print "Checked : option for release mail send"

    #2) Check download Server
    check_result = check_release_id_option(option)
    if check_result != "TRUE":
        return check_result
    else:
        print "Checked : %s version is in %s" % (option[2], TOOLS_RELEASE_URL)

    #3) Check release txt file
    check_result = check_release_txt_file(option)
    if check_result != "TRUE":
        return check_result
    else:
        print "Checked : release txt files are in %s%s" % (TOOLS_RELEASE_URL, option[2] )

    return check_result

def main(option):
    """
    Script entry point.
    Parameters:
       project - type of project for release
       release_id - release version
       destination - code release destination ( staging or download.tizen.org )
       update_latest_release ( version update or not )

    """
    if len(option) < 5:
        print "Need more input data"
        return  0

    script=option[0]
    project = option[1]
    release_id = option[2]
    destination = option[3]
    update_latest_release = option[4]


    #  Before Send mail , must check condition ( test result, public download server , and so on )
    check_result = mail_send_condion_check(option)

    if  check_result == 'TRUE':
        print "Create release mail body"
        send_mail_tool_release_message(release_id)
    else:
        print "Mail send condition is wrong"
        print check_result

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

