#!/usr/bin/python
# checksysreport, a tool to spot unsupported issues.
# Copyright 2005 Pierre Amadio 
# pamadio@redhat.com
#
# 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.
#
# 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 check request that were put by the php pages.

"""
import sys
"""http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65235"""
import os
#http://docs.python.org/lib/module-tarfile.html
import tarfile
import re
import smtplib
sys.path.append('/usr/share/checksysreport')
import globals
#from Filetype import ft_detect
#import MySQLdb.cursors
uploadDir="/var/www/checksysreport-spool"
tmpDir="/home/checksysreport"

db=globals.db_cursor
db.execute("SELECT * FROM Status")
res=db.fetchone()
status=res[1]

if status!="idle":
    print "Another cron job seems to be running"
    sys.exit()

db.execute("update status set status='busy' ")

db.execute('select id,email,arch,crm,orig_file_name from Spool order by request_date')

resdic=globals.sql_array_to_dic(\
    db.fetchall(),['id','email','arch','crm','orig_file_name'])


for cur in resdic:
    id=cur['id']
    email=cur['email']
    arch=cur['arch']
    crm=cur['crm']
    orig_name=cur['orig_file_name']
    output="Subject: checksysreport for crm "+str(crm)+"\n\n"

    sysreportFile=uploadDir+"/"+str(id)+"-"+orig_name
    print "id=",str(id)
    print "orig=",orig_name
    print "sysrreportfile=",sysreportFile
    print "email=",email
    
    
    if re.compile("^.*\.xz$").search(sysreportFile):
        print "RHEL6 xz compressed file"
        base_name=re.compile("(^.*)\.xz").search(orig_name).group(1)
        print base_name
        new_name="%s/%d-%s"%(uploadDir,id,base_name)
        cmd="/usr/bin/xzdec %s > %s"%(sysreportFile,new_name)
        pipe=os.popen(cmd,'r')
        pipe.close()


        cmd="rm "+sysreportFile
        pipe=os.popen(cmd,'r')
        pipe.close()
        sysreportFile=new_name

    isTarfile=False
    try:
        isTarfile=tarfile.is_tarfile(sysreportFile)
    except :
        isTarfile=False
        

    if isTarfile :
        tar = tarfile.open(sysreportFile,'r')
        print "tar=",tar
        basename=""
        tar.debug=1
        try:
            for tarinfo in tar:
                try:
                    tmpname=tarinfo.name
                    if re.compile(r"\.\.").search(tmpname):
                        print "No way i'm going to uncompress a file with a '..' path"
                        print "Ignoring %s",tmpname
                        continue

                    fullname=tmpDir+"/"+tmpname
                    tar.extract(tarinfo,tmpDir)
                    os.chmod(fullname,0777)
                    regexp=re.compile(r"^([^/]+)/")
                    if regexp.search(tmpname):
                        basename=regexp.search(tmpname).group(1)
                except:
                    print "Problem uncompressing ",tarinfo.name

                
            tar.close()
        except: 
            output=output+"\n**** Warning : Problem extracting %s ***"%tarinfo
            print "**** Warning : Problem extracting %s ***"%tarinfo
            
        uncompressDir=tmpDir+"/"+basename
        if arch=='autodetect' :
            cmd="checksysreport -s "+uncompressDir
        else:
            cmd="checksysreport -a "+arch+" -s "+uncompressDir
        print cmd
        pipe=os.popen(cmd,'r')
        for p in pipe:
            output=output+p
            
        pipe.close()
        cmd="rm -rf "+uncompressDir
        pipe=os.popen(cmd,'r')
        pipe.close()

    else:
        output+="There was a problem detarring the sysreport archive"


    cmd="rm "+sysreportFile
    pipe=os.popen(cmd,'r')
    pipe.close()
    
    db.execute("delete from Spool where id=%(id)d",{'id':int(id)})


    """
    Sometimes bad things can happen to the local smtp server.
    We need not to die there because if we do, the status
    field will not be cleaned in the database.
    
    Traceback (most recent call last):
     File "/usr/bin/wcs", line 122, in ?
      server = smtplib.SMTP("localhost")
     File "/usr/lib/python2.3/smtplib.py", line 240, in __init__
      (code, msg) = self.connect(host, port)
     File "/usr/lib/python2.3/smtplib.py", line 302, in connect
      raise socket.error, msg
    socket.error: (111, 'Connection refused')
                      
    
    """
    try:
        server = smtplib.SMTP("localhost")
        #server.set_debuglevel(1)
        server.sendmail('pamadio@redhat.com',email,output)
        server.quit()
    except:
        print "Problem sending mail"
        print sys.exc_info()

 

db.execute("update Status set status='idle'")
globals.db.commit()
#print Results
