summaryrefslogtreecommitdiffstats
path: root/host/utils/uhd_images_downloader.py.in
blob: bb082190cd0c96a54e73346ba7e3d56b04c41742 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
#!/usr/bin/env python
#
# Copyright 2012-2013 Ettus Research LLC
#
# 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 atexit
import hashlib
from optparse import OptionParser
import os
import os.path
import shutil
import string
import sys
import tempfile
import urllib2
import zipfile

def md5Checksum(filePath):
    with open(filePath, 'rb') as fh:
        m = hashlib.md5()
        while True:
            data = fh.read(8192)
            if not data:
                break
            m.update(data)
        return m.hexdigest()

class temp_dir():

    def __enter__(self):
        self.name = tempfile.mkdtemp()
        return self.name
    def __exit__(self, type, value, traceback):
        try:
            shutil.rmtree(self.name)
        except OSError,e:
            #Utility should have already detected this, but this is for safety
            print str(e)
            raise Exception("Could not install images! Make sure you have write permissions.")

if __name__ == "__main__":

    print
    if os.environ.get("UHD_IMAGES_DIR") != None and os.environ.get("UHD_IMAGES_DIR") != "":
        default_images_dir = os.environ.get("UHD_IMAGES_DIR")
        print "UHD_IMAGES_DIR environment variable is set. Default install location: %s" % default_images_dir
    else:
        default_images_dir = "@CMAKE_INSTALL_PREFIX@/share/uhd/images"

    #Command line options
    parser = OptionParser()
    parser.add_option("--install-location", type="string", default=default_images_dir, help="Set custom install location for images")
    parser.add_option("--buffer-size", type="int", default=8192, help="Set download buffer size, [default=%default]",)
    (options, args) = parser.parse_args()
    
    #Configuring image download info
    images_src = "@UHD_IMAGES_DOWNLOAD_SRC@"
    images_zip_md5sum = "@UHD_IMAGES_MD5SUM@"
    filename = images_src.split("/")[-1]

    #Use this directory with relative paths
    current_directory = os.getcwd()

    with temp_dir() as dirname:
        os.chdir(dirname)

        if os.path.isabs(options.install_location):
            #Custom absolute path given
            images_dir = options.install_location
        else:
            #Custom relative path given, so construct absolute path
            images_dir = os.path.abspath(os.path.join(current_directory, options.install_location))

        #Before doing anything, check for write permissions in parent directory
        parent_directory = os.path.dirname(images_dir)
        if os.access(parent_directory, os.W_OK):
            print "Downloading images to: %s" % images_dir
        else:
            print "You do not have write permissions at the install location!"
            sys.exit(1)

        opener = urllib2.build_opener()
        opener.add_headers = [('User-Agent', 'UHD Images Downloader')]
        u = opener.open(images_src)
        f = open(filename, "wb")
        meta = u.info()
        filesize = float(meta.getheaders("Content-Length")[0])
        
        print "Downloading images from: %s" % images_src
        
        filesize_dl = 0.0

        #Downloading file    
        while True:
            buffer = u.read(options.buffer_size)
            if not buffer:
                break
        
            filesize_dl -= len(buffer)
            f.write(buffer)

            status = r"%2.2f MB/%2.2f MB (%3.2f" % (-filesize_dl/1e6, filesize/1e6, (-filesize_dl*100.)/filesize) + r"%)"
            status += chr(8)*(len(status)+1)
            print status,
        
        f.close()

        #Checking md5sum of zip file
        downloaded_zip_md5sum = md5Checksum(filename)
        if images_zip_md5sum != downloaded_zip_md5sum:
            print "\nMD5 checksum does not match!"
            print "Expected %s, got %s" % (images_zip_md5sum, downloaded_zip_md5sum)
            print "Images did not install. If problem persists, please contact support@ettus.com."
            os.remove(filename)
            os.chdir("/".join(images_dir.split("/")[:-1]))
            sys.exit(1)
        else:
            temp_path = "tempdir"

            #Extracting contents of zip file
            if os.path.exists(temp_path):
                shutil.rmtree(temp_path)
            os.mkdir(temp_path)

            images_zip = zipfile.ZipFile(filename)
            images_zip.extractall(temp_path)

            #Removing images currently in images_dir
            if os.path.exists(images_dir):
                try:
                    shutil.rmtree(images_dir)
                except OSError,e:
                    print str(e)
                    print "Make sure you have write permissions in the images directory."
                    sys.exit(1)

            #Copying downloaded images into images_dir
            shutil.copytree(os.path.join(temp_path, os.path.splitext(filename)[0], 'share', 'uhd', 'images'), images_dir)

            #Removing tempdir and zip file
            shutil.rmtree(temp_path)
            images_zip.close()
            os.remove(filename)

            os.chdir(images_dir)
            print "\n\nImages successfully installed!"