#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import commands
import os
import re
import urllib
import urllib2

"""
这段脚本能帮你自动下载安装最新版的rails,如果缺少相关的gem包则递归下载相应的gem包,直到安装成功为止
by BCCN.静夜思 2011.11.11
尊重他人劳动,转载请保留本段注释

使用方法:
新建一空文件夹,把本段代码保存为install_rails.py,如
mkdir newdir
cd newdir
sudo python install_rails.py
"""

def getcontent(url):
    """爬虫函数"""
    request = urllib2.Request(url)
    request.add_header('User-Agent', 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)')
    try:
        content = urllib2.urlopen(request).read()
    except Exception, e:
        content = e
    return content

def install(gem):
    if not re.search("%s[\-\d\.]+gem"%gem, str(os.listdir('.')), re.I|re.S):
        html = getcontent("http://rubygems.org/gems/%s"%gem)
        downurl = re.search('<a href="([^\"]+)" id="download">Download</a>', html, re.I|re.S).groups()[0]
        downurl = "http://rubygems.org" + downurl
        print "download %s .................."%gem
        urllib.urlretrieve(downurl, downurl.rsplit('/',1)[1])
    gem_file = re.search("%s[\-\d\.]+gem"%gem, str(os.listdir('.')), re.I|re.S).group()
    status, result = commands.getstatusoutput("sudo gem install %s"%gem_file)
    if 'ERROR' in result and 'dependencies' in result:
        for require_gem in re.findall(' ([0-9a-zA-Z\-]+) \([=~>]', result, re.I|re.S):
            install(require_gem)
        os.system("sudo gem install %s"%gem_file)
if __name__ == "__main__":
    install("rails")