#!/usr/bin/env python
#
#    Copyright (c) 2011 Esteban Carreras Genis. All rights reserved.
#    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, either version 3 of the License, or
#    (at your option) any later version.
#
#    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, see <http://www.gnu.org/licenses/>.
#

import sys
import argparse
import urllib2 
from BeautifulSoup import BeautifulSoup as Soup

def getLink( url, level, deep ):
    """Function getLink
       Description: 
       Print n-deep links of an url
    
       Parameters:
       url -- link to crawl (string)
       level -- level that stay the crawler (int)
       deep -- deep introduced by the user (int)
       
       Returns: 
       Print the links
       
    """
    print level*"* " + url
    if level < deep:
        level = level + 1
        user_agent = """ Mozilla /5.0 ( X11 ; U ; Linux x86_64 ; en -
        US ) AppleWebKit /534.7 ( KHTML , like Gecko ) Chrome
        /7.0.517.41 Safari /534.7 """
        _opener = urllib2 . build_opener()
        _opener.addheaders = [('User - agent' , user_agent ) ]
        raw_code = _opener.open(myurl).read()
        soup_code = Soup(raw_code)
        links = [ link['href'] for link in soup_code.findAll('a')
        if link.has_key('href') ]
        for i in links:
            #Only complete urls
            if i.startswith("http"): 
                getLink(i, level, deep)
    return

#Begin the script
try:
    #Arguments of the script
    parser = argparse.ArgumentParser(description = "This program allows you to crawl an url with the main target to get each of the links that the url contains.  Allows to get the links of the levels that you want." )
    parser.add_argument ('url', nargs =1 , help = 'target URL')
    parser.add_argument ( '-n' , '--number-of-levels' , type = int , default =1 ,
    help = 'how deep the crawl will go')
    
    #Obtain the arguments
    args = parser.parse_args()
    myurl = args.url.pop()
    deep = args.number_of_levels
    
    print "This will be the main script of ecarrerasg_crawler"
    #Comprobations
    if deep <= 0:
        print 'ERROR: deep can''t be zero or less'
        sys.exit(0)
    
    #Initialization
    level = 1
    
    print "Loading links..."
    #Getting the links
    getLink(myurl, level, deep)
    
    print 'The End!!!'
   
#Exceptions  
except IOError, msg:
    parser.error(str(msg))
        
except ValueError:
    print 'ERROR: One of the parameters have an incorrect value'
        
#Ordenate finish
finally:
    sys.exit(0)

