enigma2 (20111110 rel32 -> 20120210 rel32)
[enigma2.git] / usr / lib / enigma2 / python / Components / Harddisk.py
1 from os import system, listdir, statvfs, popen, makedirs, stat, major, minor, path, access, readlink, symlink, rmdir, unlink, rename
2 from Tools.Directories import SCOPE_HDD, resolveFilename
3 from Tools.BoundFunction import boundFunction
4 from Tools.CList import CList
5 from SystemInfo import SystemInfo
6 import time
7 import re, shutil
8 from Components.Console import Console
9 from config import config, configfile, ConfigYesNo, ConfigText, ConfigSubDict, ConfigSubsection, ConfigBoolean
10
11 def MajorMinor(path):
12         rdev = stat(path).st_rdev
13         return (major(rdev),minor(rdev))
14
15 def readFile(filename):
16         file = open(filename)
17         data = file.read().strip()
18         file.close()
19         return data
20
21 DEVTYPE_UDEV = 0
22 DEVTYPE_DEVFS = 1
23
24 class Harddisk:
25         def __init__(self, device, removable = False):
26                 self.device = device
27                 self.isRemovable = removable
28
29                 if access("/dev/.udev", 0):
30                         self.type = DEVTYPE_UDEV
31                 elif access("/dev/.devfsd", 0):
32                         self.type = DEVTYPE_DEVFS
33                 else:
34                         print "Unable to determine structure of /dev"
35
36                 self.max_idle_time = 0
37                 self.idle_running = False
38                 self.timer = None
39
40                 self.dev_path = ''
41                 self.disk_path = ''
42                 self.phys_path = path.realpath(self.sysfsPath('device'))
43
44                 if self.type == DEVTYPE_UDEV:
45                         self.dev_path = '/dev/' + self.device
46                         self.disk_path = self.dev_path
47
48                 elif self.type == DEVTYPE_DEVFS:
49                         tmp = readFile(self.sysfsPath('dev')).split(':')
50                         s_major = int(tmp[0])
51                         s_minor = int(tmp[1])
52                         for disc in listdir("/dev/discs"):
53                                 dev_path = path.realpath('/dev/discs/' + disc)
54                                 disk_path = dev_path + '/disc'
55                                 try:
56                                         rdev = stat(disk_path).st_rdev
57                                 except OSError:
58                                         continue
59                                 if s_major == major(rdev) and s_minor == minor(rdev):
60                                         self.dev_path = dev_path
61                                         self.disk_path = disk_path
62                                         break
63
64                 print "new Harddisk", self.device, '->', self.dev_path, '->', self.disk_path
65                 if not self.isRemovable:
66                         self.startIdle()
67
68         def __lt__(self, ob):
69                 return self.device < ob.device
70
71         def partitionPath(self, n):
72                 if self.type == DEVTYPE_UDEV:
73                         return self.dev_path + n
74                 elif self.type == DEVTYPE_DEVFS:
75                         return self.dev_path + '/part' + n
76
77         def sysfsPath(self, filename):
78                 return path.realpath('/sys/block/' + self.device + '/' + filename)
79
80         def stop(self):
81                 if self.timer:
82                         self.timer.stop()
83                         self.timer.callback.remove(self.runIdle)
84
85         def bus(self):
86                 # CF (7025 specific)
87                 if self.type == DEVTYPE_UDEV:
88                         ide_cf = False  # FIXME
89                 elif self.type == DEVTYPE_DEVFS:
90                         ide_cf = self.device[:2] == "hd" and "host0" not in self.dev_path
91
92                 internal = "pci" in self.phys_path
93
94                 if ide_cf:
95                         ret = "External (CF)"
96                 elif internal:
97                         ret = "Internal"
98                 else:
99                         ret = "External"
100                 return ret
101
102         def bus_type(self):
103                 # CF (7025 specific)
104                 if self.type == DEVTYPE_UDEV:
105                         ide_cf = False  # FIXME
106                 elif self.type == DEVTYPE_DEVFS:
107                         ide_cf = self.device[:2] == "hd" and "host0" not in self.dev_path
108                         
109                 sata = "pci" in self.phys_path
110                 sata_desc = self.bus_description()
111
112                 if ide_cf:
113                         ret = "IDE"
114                 elif sata:
115                         if sata_desc is not None:
116                                 ret = sata_desc
117                         else:
118                                 ret = "SATA"
119                 else:
120                         ret = "USB"
121                 return ret
122
123         def bus_description(self):
124                 phys = self.phys_path[4:]
125                 from Tools.HardwareInfo import HardwareInfo
126                 if self.device.find('sr') == 0 and self.device[2].isdigit():
127                         devicedb = DEVICEDB_SR
128                 else:
129                         devicedb = DEVICEDB
130
131                 for physdevprefix, pdescription in devicedb.get(HardwareInfo().device_name,{}).items():
132                         if phys.startswith(physdevprefix):
133                                 return pdescription
134                 if phys.find('pci') != -1:
135                         return "SATA"
136                 elif phys.find('usb') != -1:
137                         return "USB"
138                 return "External Storage"
139
140         def diskSize(self):
141                 try:
142                         line = readFile(self.sysfsPath('size'))
143                         cap = int(line)
144                 except:
145                         return 0;
146                 return cap / 1000 * 512 / 1000
147
148         def capacity(self):
149                 cap = self.diskSize()
150                 if cap == 0:
151                         return ""
152                 return "%d.%03d GB" % (cap/1000, cap%1000)
153
154         def model(self, model_only = False, vendor_only = False):
155                 if self.device[:2] == "hd":
156                         return readFile('/proc/ide/' + self.device + '/model')
157                 elif self.device[:2] == "sd":
158                         try:
159                                 vendor = readFile(self.sysfsPath('device/vendor'))
160                                 model = readFile(self.sysfsPath('device/model'))
161                         except:
162                                 vendor = ""
163                                 model = ""
164                                 
165                         if vendor_only:
166                                 return vendor
167                         if model_only:
168                                 return model
169                         return vendor + '-' + model
170                 else:
171                         assert False, "no hdX or sdX"
172
173         def free(self):
174                 try:
175                         mounts = open("/proc/mounts")
176                 except IOError:
177                         return -1
178
179                 lines = mounts.readlines()
180                 mounts.close()
181
182                 for line in lines:
183                         parts = line.strip().split(" ")
184                         real_path = path.realpath(parts[0])
185                         if not real_path[-1].isdigit():
186                                 continue
187                         try:
188                                 if MajorMinor(real_path) == MajorMinor(self.partitionPath(real_path[-1])):
189                                         stat = statvfs(parts[1])
190                                         return stat.f_bfree/1000 * stat.f_bsize/1000
191                         except OSError:
192                                 pass
193                 return -1
194
195         def numPartitions(self):
196                 numPart = -1
197                 if self.type == DEVTYPE_UDEV:
198                         try:
199                                 devdir = listdir('/dev')
200                         except OSError:
201                                 return -1
202                         for filename in devdir:
203                                 if filename.startswith(self.device):
204                                         numPart += 1
205
206                 elif self.type == DEVTYPE_DEVFS:
207                         try:
208                                 idedir = listdir(self.dev_path)
209                         except OSError:
210                                 return -1
211                         for filename in idedir:
212                                 if filename.startswith("disc"):
213                                         numPart += 1
214                                 if filename.startswith("part"):
215                                         numPart += 1
216                 return numPart
217
218         def unmount(self, numpart = None):
219                 try:
220                         mounts = open("/proc/mounts")
221                 except IOError:
222                         return -1
223
224                 lines = mounts.readlines()
225                 mounts.close()
226
227                 cmd = "umount"
228                 for line in lines:
229                         parts = line.strip().split(" ")
230                         real_path = path.realpath(parts[0])
231                         if not real_path[-1].isdigit():
232                                 if numpart is not None and numpart == 0:
233                                         if real_path.startswith("/dev/sd"):
234                                                 uuid = harddiskmanager.getPartitionUUID(self.device)
235                                                 if uuid is not None:
236                                                         try:
237                                                                 if MajorMinor(real_path) == MajorMinor(self.dev_path):
238                                                                         cmd = ' ' . join([cmd, parts[1]])
239                                                                         break
240                                                         except OSError:
241                                                                 pass
242                         try:
243                                 if MajorMinor(real_path) == MajorMinor(self.partitionPath(real_path[-1])):
244                                         cmd = ' ' . join([cmd, parts[1]])
245                                         break
246                         except OSError:
247                                 pass
248                 res = system(cmd)
249                 if cmd == "umount": # nothing found to unmount
250                         res = 0
251                 return (res >> 8)
252
253         def createPartition(self, numpart):
254                 #gpt partitiontype support currently disabled.
255                 """devicename = self.device + "1"
256                 if numpart is not None:
257                         if numpart == 0:
258                                 devicename = self.device
259                         if numpart >= 1:
260                                 devicename = self.device + (str(numpart))
261                 type, sys, size, sizeg = harddiskmanager.getFdiskInfo(devicename)"""
262
263                 cmd = 'printf "8,\n;0,0\n;0,0\n;0,0\ny\n" | sfdisk -f -uS ' + self.disk_path
264
265                 #if sys is not None and "GPT" in sys:
266                 #       cmd = 'printf "34,,'+type+'\n;0,0\n;0,0\n;0,0\ny\n" | sfdisk -f -uS ' + self.disk_path
267
268                 res = system(cmd)
269                 return (res >> 8)
270
271         def mkfs(self):
272                 cmd = "mkfs.ext3 "
273                 if self.diskSize() > 4 * 1024:
274                         cmd += "-T largefile "
275                 cmd += "-m0 -O dir_index " + self.partitionPath("1")
276                 res = system(cmd)
277                 return (res >> 8)
278
279         def mount(self):
280                 try:
281                         fstab = open("/etc/fstab")
282                 except IOError:
283                         return -1
284
285                 lines = fstab.readlines()
286                 fstab.close()
287
288                 res = -1
289                 for line in lines:
290                         parts = line.strip().split(" ")
291                         real_path = path.realpath(parts[0])
292                         if not real_path[-1].isdigit():
293                                 continue
294                         try:
295                                 if MajorMinor(real_path) == MajorMinor(self.partitionPath(real_path[-1])):
296                                         cmd = "mount -t auto " + parts[0]
297                                         res = system(cmd)
298                                         break
299                         except OSError:
300                                 pass
301                 return (res >> 8)
302
303         def createMovieFolder(self):
304                 try:
305                         makedirs(resolveFilename(SCOPE_HDD))
306                 except OSError:
307                         return -1
308                 return 0
309
310         def fsck(self, numpart):
311                 # We autocorrect any failures and check if the fs is actually one we can check (currently ext2/ext3)
312                 partitionPath = self.partitionPath("1")
313                 if numpart is not None:
314                         if numpart == 0:
315                                 partitionPath = self.dev_path
316                         if numpart >= 1:
317                                 partitionPath = self.partitionPath(str(numpart))
318
319                 partitionType = harddiskmanager.getBlkidPartitionType(partitionPath)                            
320
321                 res = -1
322                 if access(partitionPath, 0):
323                         if partitionType is not None and partitionType in ("ext2", "ext3"):
324                                 cmd = "fsck." + partitionType + " -f -p " + partitionPath
325                                 res = system(cmd)
326                 return (res >> 8)
327
328         def killPartition(self, n):
329                 part = self.partitionPath("1")
330                 if n is not None:
331                         if n == 0:
332                                 part = self.disk_path
333                         if n >= 1:
334                                 part = self.partitionPath(str(n))
335                 if access(part, 0):
336                         #cmd = 'dd bs=512 count=3 if=/dev/zero of=' + part
337                         cmd = 'dd bs=4k count=3 if=/dev/zero of=' + part
338                         res = system(cmd)
339                 else:
340                         res = 0
341                 return (res >> 8)
342
343         errorList = [ _("Everything is fine"), _("Creating partition failed"), _("Mkfs failed"), _("Mount failed"), _("Create movie folder failed"), _("Fsck failed"), _("Please Reboot"), _("Filesystem contains uncorrectable errors"), _("Unmount failed")]
344
345         def initialize(self, isFstabMounted = False, numpart = None):
346                 if self.unmount(numpart) != 0:
347                         return -8
348                 # Udev tries to mount the partition immediately if there is an
349                 # old filesystem on it when fdisk reloads the partition table.
350                 # To prevent that, we overwrite the first sectors of the
351                 # partitions, if the partition existed before. This should work
352                 # for ext2/ext3 and also for GPT/EFI partitions.
353                 if numpart is not None:
354                         for p in range(numpart+1):
355                                 self.killPartition(p)
356                 else:
357                         self.killPartition(1)
358
359                 if self.createPartition(numpart) != 0:
360                         return -1
361                 
362                 if self.mkfs() != 0:
363                         return -2
364
365                 if isFstabMounted:
366                         if self.mount() != 0:
367                                 return -3
368                         if self.createMovieFolder() != 0:
369                                 return -4
370
371                 return 0
372
373         def check(self, isFstabMounted = False, numpart = None):
374                 
375                 if self.unmount(numpart) != 0:
376                         return -8
377
378                 res = self.fsck(numpart)
379                 if res & 2 == 2:
380                         return -6
381
382                 if res & 4 == 4:
383                         return -7
384
385                 if res != 0 and res != 1:
386                         # A sum containing 1 will also include a failure
387                         return -5
388                 
389                 if isFstabMounted:
390                         if self.mount() != 0:
391                                 return -3
392
393                 return 0
394
395         def getDeviceDir(self):
396                 return self.dev_path
397
398         def getDeviceName(self):
399                 return self.disk_path
400
401         # the HDD idle poll daemon.
402         # as some harddrives have a buggy standby timer, we are doing this by hand here.
403         # first, we disable the hardware timer. then, we check every now and then if
404         # any access has been made to the disc. If there has been no access over a specifed time,
405         # we set the hdd into standby.
406         def readStats(self):
407                 try:
408                         l = open("/sys/block/%s/stat" % self.device).read()
409                 except IOError:
410                         return -1,-1
411                 (nr_read, _, _, _, nr_write) = l.split()[:5]
412                 return int(nr_read), int(nr_write)
413
414         def startIdle(self):
415                 self.last_access = time.time()
416                 self.last_stat = 0
417                 self.is_sleeping = False
418                 from enigma import eTimer
419
420                 # disable HDD standby timer
421                 if self.bus() == "External":
422                         Console().ePopen(("sdparm", "sdparm", "--set=SCT=0", self.disk_path))
423                 else:
424                         Console().ePopen(("hdparm", "hdparm", "-S0", self.disk_path))
425                 self.timer = eTimer()
426                 self.timer.callback.append(self.runIdle)
427                 self.idle_running = True
428                 self.setIdleTime(self.max_idle_time) # kick the idle polling loop
429
430         def runIdle(self):
431                 if not self.max_idle_time:
432                         return
433                 t = time.time()
434
435                 idle_time = t - self.last_access
436
437                 stats = self.readStats()
438                 print "nr_read", stats[0], "nr_write", stats[1]
439                 l = sum(stats)
440                 print "sum", l, "prev_sum", self.last_stat
441
442                 if l != self.last_stat and l >= 0: # access
443                         print "hdd was accessed since previous check!"
444                         self.last_stat = l
445                         self.last_access = t
446                         idle_time = 0
447                         self.is_sleeping = False
448                 else:
449                         print "hdd IDLE!"
450
451                 print "[IDLE]", idle_time, self.max_idle_time, self.is_sleeping
452                 if idle_time >= self.max_idle_time and not self.is_sleeping:
453                         self.setSleep()
454                         self.is_sleeping = True
455
456         def setSleep(self):
457                 if self.bus() == "External":
458                         Console().ePopen(("sdparm", "sdparm", "--command=stop", self.disk_path))
459                 else:
460                         Console().ePopen(("hdparm", "hdparm", "-y", self.disk_path))
461
462         def setIdleTime(self, idle):
463                 self.max_idle_time = idle
464                 if self.idle_running:
465                         if not idle:
466                                 self.timer.stop()
467                         else:
468                                 self.timer.start(idle * 100, False)  # poll 10 times per period.
469
470         def isSleeping(self):
471                 return self.is_sleeping
472
473 class Partition:
474         def __init__(self, mountpoint, device = None, description = "", force_mounted = False):
475                 self.mountpoint = mountpoint
476                 self.description = description
477                 self.force_mounted = force_mounted
478                 self.is_hotplug = force_mounted # so far; this might change.
479                 self.device = device
480                 self.disc_path = None
481                 self.uuid = None
482
483         def stat(self):
484                 return statvfs(self.mountpoint)
485
486         def free(self):
487                 try:
488                         s = self.stat()
489                         return s.f_bavail * s.f_bsize
490                 except OSError:
491                         return None
492
493         def total(self):
494                 try:
495                         s = self.stat()
496                         return s.f_blocks * s.f_bsize
497                 except OSError:
498                         return None
499
500         def mounted(self):
501                 # THANK YOU PYTHON FOR STRIPPING AWAY f_fsid.
502                 # TODO: can os.path.ismount be used?
503                 if self.force_mounted:
504                         return True
505
506                 try:
507                         mounts = open("/proc/mounts")
508                 except IOError:
509                         return False
510
511                 lines = mounts.readlines()
512                 mounts.close()
513
514                 for line in lines:
515                         if line.split(' ')[1] == self.mountpoint:
516                                 return True
517                 return False
518
519
520 DEVICEDB_SR = \
521         {"dm8000":
522                 {
523                         "/devices/pci0000:01/0000:01:00.0/host0/target0:0:0/0:0:0:0": _("DVD Drive"),
524                         "/devices/pci0000:01/0000:01:00.0/host1/target1:0:0/1:0:0:0": _("DVD Drive"),
525                         "/devices/platform/brcm-ehci-1.1/usb2/2-1/2-1:1.0/host3/target3:0:0/3:0:0:0": _("DVD Drive"),
526                 },
527         "dm800":
528         {
529         },
530         "dm7025":
531         {
532         }
533         }
534
535 DEVICEDB = \
536         {"dm8000":
537                 {
538                         "/devices/pci0000:01/0000:01:00.0/host1/target1:0:0/1:0:0:0": _("SATA"),
539                         "/devices/platform/brcm-ehci.0/usb1/1-1/1-1.1/1-1.1:1.0": _("Front USB"),
540                         "/devices/platform/brcm-ehci.0/usb1/1-1/1-1.1/1-1.1.": _("Front USB"),
541                         "/devices/platform/brcm-ehci.0/usb1/1-1/1-1.2/1-1.2:1.0": _("Back, upper USB"),
542                         "/devices/platform/brcm-ehci.0/usb1/1-1/1-1.2/1-1.2.": _("Back, upper USB"),
543                         "/devices/platform/brcm-ehci.0/usb1/1-1/1-1.3/1-1.3:1.0": _("Back, lower USB"),
544                         "/devices/platform/brcm-ehci.0/usb1/1-1/1-1.3/1-1.3.": _("Back, lower USB"),
545                         "/devices/platform/brcm-ehci-1.1/usb2/2-1/2-1:1.0/": _("Internal USB"),
546                         "/devices/platform/brcm-ohci-1.1/usb4/4-1/4-1:1.0/": _("Internal USB"),
547                         "/devices/platform/brcm-ehci.0/usb1/1-1/1-1.4/1-1.4.": _("Internal USB"),
548                 },
549         "dm7020hd":
550         {
551                 "/devices/pci0000:01/0000:01:00.0/host0/target0:0:0/0:0:0:0": _("SATA"),
552                 "/devices/pci0000:01/0000:01:00.0/host1/target1:0:0/1:0:0:0": _("eSATA"),
553                 "/devices/platform/brcm-ehci-1.1/usb2/2-1/2-1:1.0": _("Front USB"),
554                 "/devices/platform/brcm-ehci-1.1/usb2/2-1/2-1.": _("Front USB"),
555                 "/devices/platform/brcm-ehci.0/usb1/1-2/1-2:1.0": _("Back, upper USB"),
556                 "/devices/platform/brcm-ehci.0/usb1/1-2/1-2.": _("Back, upper USB"),
557                 "/devices/platform/brcm-ehci.0/usb1/1-1/1-1:1.0": _("Back, lower USB"),
558                 "/devices/platform/brcm-ehci.0/usb1/1-1/1-1.": _("Back, lower USB"),
559         },
560         "dm800":
561         {
562                 "/devices/pci0000:01/0000:01:00.0/host0/target0:0:0/0:0:0:0": _("SATA"),
563                 "/devices/platform/brcm-ehci.0/usb1/1-2/1-2:1.0": _("Upper USB"),
564                 "/devices/platform/brcm-ehci.0/usb1/1-1/1-1:1.0": _("Lower USB"),
565         },
566         "dm800se":
567         {
568                 "/devices/pci0000:01/0000:01:00.0/host0/target0:0:0/0:0:0:0": _("SATA"),
569                 "/devices/pci0000:01/0000:01:00.0/host1/target1:0:0/1:0:0:0": _("eSATA"),
570                 "/devices/platform/brcm-ehci.0/usb1/1-2/1-2:1.0": _("Upper USB"),
571                 "/devices/platform/brcm-ehci.0/usb1/1-1/1-1:1.0": _("Lower USB"),
572         },
573         "dm500hd":
574         {
575                 "/devices/pci0000:01/0000:01:00.0/host1/target1:0:0/1:0:0:0": _("eSATA"),
576                 "/devices/pci0000:01/0000:01:00.0/host0/target0:0:0/0:0:0:0": _("eSATA"),
577         },
578         "dm7025":
579         {
580                 "/devices/pci0000:00/0000:00:14.1/ide1/1.0": "Compact Flash", #hdc
581                 "/devices/pci0000:00/0000:00:14.1/ide0/0.0": "Internal Harddisk"
582         }
583         }
584
585 class HarddiskManager:
586         def __init__(self):
587                 config.storage_options = ConfigSubsection()
588                 config.storage_options.default_device = ConfigText(default = "<undefined>")
589                 config.storage = ConfigSubDict()
590                 self.hdd = [ ]
591                 self.cd = ""
592                 self.partitions = [ ]
593                 self.devices_scanned_on_init = [ ]
594                 self.delayed_device_Notifier = [ ]
595
596                 self.on_partition_list_change = CList()
597                 
598                 # currently, this is just an enumeration of what's possible,
599                 # this probably has to be changed to support automount stuff.
600                 # still, if stuff is mounted into the correct mountpoints by
601                 # external tools, everything is fine (until somebody inserts
602                 # a second usb stick.)
603                 p = [
604                                         ("/media/hdd", _("Hard disk")),
605                                         ("/media/card", _("Card")),
606                                         ("/media/cf", _("Compact Flash")),
607                                         ("/media/mmc1", _("SD/MMC")),
608                                         ("/media/net", _("Network Mount")),
609                                         ("/media/ram", _("Ram Disk")),
610                                         ("/media/usb", _("USB Stick")),
611                                         ("/", _("Internal Flash"))
612                                 ]
613                 self.partitions.extend([ Partition(mountpoint = x[0], description = x[1]) for x in p ])
614
615                 self.setupConfigEntries(initial_call = True)
616
617                 self.enumerateBlockDevices()
618
619         def getBlockDevInfo(self, blockdev):
620                 devpath = "/sys/block/" + blockdev
621                 error = False
622                 removable = False
623                 blacklisted = False
624                 is_cdrom = False
625                 partitions = []
626                 try:
627                         removable = bool(int(readFile(devpath + "/removable")))
628                         dev = int(readFile(devpath + "/dev").split(':')[0])
629                         if dev in (7, 31): # loop, mtdblock
630                                 blacklisted = True
631                         if blockdev[0:2] == 'sr':
632                                 is_cdrom = True
633                         if blockdev[0:2] == 'hd':
634                                 try:
635                                         media = readFile("/proc/ide/%s/media" % blockdev)
636                                         if "cdrom" in media:
637                                                 is_cdrom = True
638                                 except IOError:
639                                         error = True
640                         # check for partitions
641                         if not is_cdrom:
642                                 for partition in listdir(devpath):
643                                         if partition[0:len(blockdev)] != blockdev:
644                                                 continue
645                                         partitions.append(partition)
646                         else:
647                                 self.cd = blockdev
648                 except IOError:
649                         error = True
650                 # check for medium
651                 medium_found = True
652                 try:
653                         open("/dev/" + blockdev).close()
654                 except IOError, err:
655                         if err.errno == 159: # no medium present
656                                 medium_found = False
657                 return error, blacklisted, removable, is_cdrom, partitions, medium_found
658
659         def enumerateBlockDevices(self):
660                 print "enumerating block devices..."
661                 for blockdev in listdir("/sys/block"):
662                         error, blacklisted, removable, is_cdrom, partitions, medium_found = self.addHotplugPartition(blockdev)
663                         if not error and not blacklisted:
664                                 if medium_found:
665                                         for part in partitions:
666                                                 self.addHotplugPartition(part)
667                                 self.devices_scanned_on_init.append((blockdev, removable, is_cdrom, medium_found))
668                                 print "[enumerateBlockDevices] devices_scanned_on_init:",self.devices_scanned_on_init
669
670         def getAutofsMountpoint(self, device):
671                 return "/autofs/%s/" % (device)
672
673         def is_hard_mounted(self, device):
674                 mounts = file('/proc/mounts').read().split('\n')
675                 for x in mounts:
676                         if x.find('/autofs') == -1 and x.find(device) != -1:
677                                 #print "is_hard_mounted:",device
678                                 return True
679                 return False
680
681         def is_uuidpath_mounted(self, uuidpath, mountpoint):
682                 mounts = file('/proc/mounts').read().split('\n')
683                 for x in mounts:
684                         if not x.startswith('/'):
685                                 continue
686                         path, mp = x.split()[0:2]
687                         if (path == uuidpath and mp == mountpoint):
688                                 #print "is_uuid_mounted:'%s' for: %s " % (path, mp)
689                                 return True
690                 return False
691
692         def is_fstab_mountpoint(self, device, mountpoint):
693                 mounts = file('/etc/fstab').read().split('\n')
694                 for x in mounts:
695                         if not x.startswith('/'):
696                                 continue
697                         dev, mp = x.split()[0:2]
698                         if (dev == device and mp == mountpoint):
699                                 #print "is_fstab_mountpoint:'%s' for: %s " % (mp, dev)
700                                 return True
701                 return False
702
703         def get_fstab_mountstate(self, device, mountpoint):
704                 mounts = file('/etc/fstab').read().split('\n')
705                 for x in mounts:
706                         if not x.startswith('/'):
707                                 continue
708                         dev, mp, ms = x.split()[0:3]
709                         if (dev == device and mp == mountpoint):
710                                 #print "got_fstab_mountstate:'%s' for: %s - %s" % (ms, dev, mp)
711                                 return ms
712                 return False
713
714         def get_fstab_mountpoint(self, device):
715                 mounts = file('/etc/fstab').read().split('\n')
716                 for x in mounts:
717                         if not x.startswith('/'):
718                                 continue
719                         dev, mp = x.split()[0:2]
720                         if device == dev:
721                                 #print "got_fstab_mountpoint:'%s' for: %s" % (mp, dev)
722                                 return mp
723                 return None
724
725         def modifyFstabEntry(self, partitionPath, mountpoint, mode = "add_deactivated"):
726                 try:
727                         alreadyAdded = self.is_fstab_mountpoint(partitionPath, mountpoint)
728                         oldLine = None
729                         mounts = file('/etc/fstab').read().split('\n')
730                         fp = file("/etc/fstab", 'w')
731                         fp.write("#automatically edited by enigma2, " + str(time.strftime( "%a" + ", " + "%d " + "%b" + " %Y %H:%M:%S", time.localtime(time.time() ))) + "\n")
732                         for x in mounts:
733                                 if (x.startswith(partitionPath) and mountpoint in x):
734                                         oldLine = x
735                                         continue
736                                 if len(x):
737                                         if x.startswith('#automatically'):
738                                                 continue
739                                         fp.write(x + "\n")
740                         if not alreadyAdded:
741                                 if mode == "add_deactivated":
742                                         #print "modifyFstabEntry - add_deactivated:", partitionPath, mountpoint
743                                         fp.write(partitionPath + "\t" + mountpoint + "\tnoauto\tdefaults\t0 0\n")
744                         else:
745                                 if mode == "add_deactivated":
746                                         if oldLine is not None:
747                                                 if "noauto" in oldLine:
748                                                         fp.write(oldLine + "\n")
749                                                 else:
750                                                         #print "modifyFstabEntry - add_deactivated - changed:", partitionPath, mountpoint
751                                                         fp.write(oldLine.replace("auto","noauto") + "\n")
752                         fp.close()
753                 except:
754                         print "error adding fstab entry for: %s" % (partitionPath)
755
756         def addHotplugPartition(self, device, physdev = None):
757                 if not physdev:
758                         dev, part = self.splitDeviceName(device)
759                         try:
760                                 physdev = path.realpath('/sys/block/' + dev + '/device')[4:]
761                         except OSError:
762                                 physdev = dev
763                                 print "couldn't determine blockdev physdev for device", device
764
765                 error, blacklisted, removable, is_cdrom, partitions, medium_found = self.getBlockDevInfo(device)
766                 print "found block device '%s':" % device,
767
768                 if blacklisted:
769                         print "blacklisted"
770                 else:
771                         if error:
772                                 print "error querying properties"
773                         elif not medium_found:
774                                 print "no medium"
775                         else:
776                                 print "ok, removable=%s, cdrom=%s, partitions=%s" % (removable, is_cdrom, partitions)
777
778                         l = len(device)
779                         if l:
780                                 # see if this is a harddrive or removable drive (usb stick/cf/sd)
781                                 if not device[l-1].isdigit() and not is_cdrom:
782                                         if self.getHDD(device) is None and medium_found:
783                                                 if removable:
784                                                         self.hdd.append(Harddisk(device, True))
785                                                 else:
786                                                         self.hdd.append(Harddisk(device, False))                                                        
787                                         self.hdd.sort()
788                                         SystemInfo["Harddisk"] = len(self.hdd) > 0
789
790                                 if (not removable or medium_found) and not self.is_hard_mounted(device):
791                                         self.addDevicePartition(device, physdev)
792
793                 return error, blacklisted, removable, is_cdrom, partitions, medium_found
794
795         def removeHotplugPartition(self, device):
796                 mountpoint = self.getAutofsMountpoint(device)
797                 uuid = self.getPartitionUUID(device)
798                 print "[removeHotplugPartition] for device:'%s'" % (device)
799                 p = self.getPartitionbyDevice(device)
800                 if p is None:
801                         p = self.getPartitionbyMountpoint(mountpoint)
802                 if p is not None:
803                         if uuid is None and p.uuid is not None:
804                                 uuid = p.uuid
805                                 harddiskmanager.unmountPartitionbyMountpoint(p.mountpoint)
806                         if uuid is not None and config.storage.get(uuid, None) is not None:
807                                 self.unmountPartitionbyUUID(uuid)
808                                 if not config.storage[uuid]['enabled'].value:
809                                         del config.storage[uuid]
810                                         print "[removeHotplugPartition] - remove uuid %s from temporary drive add" % (uuid)
811                         self.partitions.remove(p)
812                         self.on_partition_list_change("remove", p)
813
814                 if (uuid is not None and uuid == config.storage_options.default_device.value):
815                         self.verifyDefaultStorageDevice(uuid)
816                         from Tools import Notifications
817                         from Screens.MessageBox import MessageBox
818                         Notifications.AddNotification(MessageBox,_("Default storage device was removed!") + "\n" \
819                                 + _("Please verify if your default storage device is attached or set up your default storage device in menu -> setup -> system -> recording paths."), MessageBox.TYPE_INFO, timeout=20)
820
821                 l = len(device)
822                 if l and not device[l-1].isdigit():
823                         for hdd in self.hdd:
824                                 if hdd.device == device:
825                                         hdd.stop()
826                                         self.hdd.remove(hdd)
827                                         break
828                         SystemInfo["Harddisk"] = len(self.hdd) > 0
829
830                         #call the notifier only after we have fully removed the disconnected drive
831                         for callback in self.delayed_device_Notifier:
832                                 try:
833                                         callback(device, "remove_delayed" )
834                                 except AttributeError:
835                                         self.delayed_device_Notifier.remove(callback)
836
837         def addDevicePartition(self, device, physdev):
838                 # device is the device name, without /dev
839                 # physdev is the physical device path, which we (might) use to determine the userfriendly name
840                 description = self.getUserfriendlyDeviceName(device, physdev)
841                 device_mountpoint = self.getAutofsMountpoint(device)
842                 uuid = self.getPartitionUUID(device)
843                 print "[addDevicePartition] device:'%s' with UUID:'%s'" % (device, uuid)
844                 if config.storage.get(uuid, None) is not None:
845                         if config.storage[uuid]['mountpoint'].value != "":
846                                 device_mountpoint = config.storage[uuid]['mountpoint'].value
847                 if uuid is not None:
848                         if config.storage.get(uuid, None) is None:
849                                 self.setupConfigEntries(initial_call = False, dev = device)
850                         else:
851                                 self.storageDeviceChanged(uuid)
852                 p = self.getPartitionbyMountpoint(device_mountpoint)
853                 if p is not None:
854                         if uuid is not None:
855                                 if p.uuid is not None and p.uuid != uuid:
856                                         if config.storage.get(p.uuid, None) is not None:
857                                                 del config.storage[p.uuid] #delete old uuid reference entries
858                         p.mountpoint = device_mountpoint
859                         p.force_mounted = False
860                         p.device = device
861                         p.uuid = uuid
862                 else:
863                         forced = True
864                         if uuid is not None:
865                                 cfg_uuid = config.storage.get(uuid, None)
866                                 if cfg_uuid is not None:
867                                         if cfg_uuid['enabled'].value:
868                                                 forced = False
869                                         else:
870                                                 device_mountpoint = self.getAutofsMountpoint(device)
871                         x = self.getPartitionbyDevice(device)
872                         if x is None:
873                                 p = Partition(mountpoint = device_mountpoint, description = description, force_mounted = forced, device = device)
874                                 p.uuid = uuid
875                                 self.partitions.append(p)
876                                 self.on_partition_list_change("add", p)
877                         else:   # found old partition entry
878                                 if config.storage.get(x.uuid, None) is not None:
879                                         del config.storage[x.uuid] #delete old uuid reference entries
880                                 x.mountpoint = device_mountpoint
881                                 x.force_mounted = True
882                                 x.uuid = uuid
883                 if p is not None:
884                         if uuid == config.storage_options.default_device.value:
885                                 self.verifyDefaultStorageDevice()
886
887                 for callback in self.delayed_device_Notifier:
888                         try:
889                                 callback(device, "add_delayed" )
890                         except AttributeError:
891                                 self.delayed_device_Notifier.remove(callback)
892
893         def HDDCount(self):
894                 return len(self.hdd)
895
896         def HDDList(self):
897                 list = [ ]
898                 for hd in self.hdd:
899                         hdd = hd.model() + " - " + hd.bus()
900                         cap = hd.capacity()
901                         if cap != "":
902                                 hdd += " (" + cap + ")"
903                         list.append((hdd, hd))
904                 return list
905
906         def HDDEnabledCount(self):
907                 cnt = 0
908                 for uuid, cfg in config.storage.items():
909                         print "uuid", uuid, "cfg", cfg
910                         if cfg["enabled"].value:
911                                 cnt += 1
912                 return cnt
913
914         def getHDD(self, part):
915                 for hdd in self.hdd:
916                         if hdd.device == part[:3]:
917                                 return hdd
918                 return None
919
920         def getCD(self):
921                 return self.cd
922
923         def getFdiskInfo(self, devname):
924                 size = sizeg = type = sys = None
925                 cmd = "fdisk -l /dev/" + devname
926
927                 try:
928                         for line in popen(cmd).read().split('\n'):
929                                 if line.startswith("Disk"):
930                                         sizeobj = re.search(r', ((?:[a-zA-Z0-9])*) bytes', line)
931                                         if sizeobj:
932                                                 size = sizeobj.group(1)
933                                         sizegobj = re.search(r': ((?:[0-9.0-9])*) GB', line)
934                                         if sizegobj:
935                                                 sizeg = sizegobj.group(1)
936                                 if not line.startswith('/'):
937                                         continue
938                                 if line.startswith("/dev/" + devname):
939                                         a,b,c,d, type, sys = line.split(None,5)
940                 except:
941                         print "error getting fdisk device info"
942                 return type, sys, size, sizeg
943
944         def getBlkidPartitionType(self, device):
945                 type = None
946                 if path.exists("/usr/sbin/blkid"):
947                         cmd = "/usr/sbin/blkid " + str(device)
948                         try:
949                                 for line in popen(cmd).read().split('\n'):
950                                         if not line.startswith(device):
951                                                 continue
952                                         fstobj = re.search(r' TYPE="((?:[^"\\]|\\.)*)"', line)
953                                         if fstobj:
954                                                 type = fstobj.group(1)
955                         except:
956                                 print "error getting blkid partition type"
957                 return type
958
959         def getLinkPath(self,link):
960                 if path.islink(link):
961                         p = path.normpath(readlink(link))
962                         if path.isabs(p):
963                                 return p
964                         return path.join(path.dirname(link), p)
965
966         def verifyDefaultStorageDevice(self, old_default = None):
967                 uuid = config.storage_options.default_device.value
968                 part = self.getdefaultStorageDevicebyUUID(uuid)
969                 defaultpath = "/media/hdd"
970                 curr_defaultpath = self.getLinkPath(defaultpath)
971                 if part is not None:
972                         if part in self.getConfiguredStorageDevices():
973                                 mountpoint = part.mountpoint
974                                 if path.ismount(mountpoint): #default storage mountpoint available ?
975                                         if (path.exists(defaultpath) and not path.islink(defaultpath) and not path.ismount(defaultpath) ):
976                                                 try:
977                                                         rmdir(defaultpath)
978                                                         print "removed /media/hdd dir"
979                                                 except OSError:
980                                                         print "could not remove /media/hdd dir"
981                                                         try:
982                                                                 rename(defaultpath,"/media/hdd_old")
983                                                                 print "renamed /media/hdd dir to /media/hdd_old"
984                                                         except OSError:
985                                                                 print "could not rename /media/hdd dir to /media/hdd_old"
986                                         if (path.islink(defaultpath) and self.getLinkPath(defaultpath) != mountpoint ):
987                                                 try:
988                                                         unlink(defaultpath)
989                                                         print "removed old default storage link"
990                                                 except OSError:
991                                                         pass
992                                         if not path.exists(defaultpath):
993                                                 try:
994                                                         symlink(mountpoint,defaultpath)
995                                                         print "default storage link created"
996                                                 except OSError:
997                                                         pass
998                                         if self.getLinkPath(defaultpath) == mountpoint:
999                                                 print "default storage device successfully linked to /media/hdd"
1000                                 if not path.ismount(mountpoint): #default storage mountpoint unavailable !
1001                                         if self.getLinkPath(defaultpath) == mountpoint:
1002                                                 try:
1003                                                         unlink(defaultpath)
1004                                                         print "removed unused /media/hdd"
1005                                                 except OSError:
1006                                                         print "could not remove unused /media/hdd link"
1007                                         if not path.exists(defaultpath):
1008                                                 print "default storage link removed"
1009                 else:
1010                         if old_default is None:
1011                                 if uuid == "<undefined>":
1012                                         if (not path.islink(defaultpath) and not path.ismount(defaultpath) ):
1013                                                 try:
1014                                                         rmdir(defaultpath)
1015                                                         print "removed undefined /media/hdd dir"
1016                                                 except OSError:
1017                                                         print "could not remove undefined /media/hdd dir"
1018                                                         try:
1019                                                                 rename(defaultpath,"/media/hdd_old")
1020                                                                 print "renamed undefined /media/hdd dir to /media/hdd_old"
1021                                                         except OSError:
1022                                                                 print "could not rename undefined /media/hdd dir to /media/hdd_old"
1023                                         if (path.islink(defaultpath) and not path.ismount(defaultpath)):
1024                                                 try:
1025                                                         unlink(defaultpath)
1026                                                         print "removed undefined default storage link"
1027                                                 except OSError:
1028                                                         print "could not remove undefined /media/hdd dir"
1029                                 elif uuid != "<undefined>":
1030                                         cfg_uuid = config.storage.get(uuid, None)
1031                                         if cfg_uuid is not None and not cfg_uuid["enabled"].value:
1032                                                 config.storage_options.default_device.value = "<undefined>"
1033                                                 config.storage_options.default_device.save()
1034                                                 config.storage_options.save()
1035                                                 mountpoint = self.getLinkPath(defaultpath)
1036                                                 uuidpath = "/dev/disk/by-uuid/" + uuid
1037                                                 if (self.is_fstab_mountpoint(uuidpath, mountpoint) and self.get_fstab_mountstate(uuidpath, mountpoint) == 'noauto'):
1038                                                         try:
1039                                                                 unlink(defaultpath)
1040                                                                 print "removed unconfigured storage device link"
1041                                                         except OSError:
1042                                                                 pass
1043                                         elif cfg_uuid is not None and cfg_uuid["enabled"].value:
1044                                                 print self.getLinkPath(defaultpath), cfg_uuid["mountpoint"].value
1045                                                 if cfg_uuid["mountpoint"].value == self.getLinkPath(defaultpath):
1046                                                         try:
1047                                                                 unlink(defaultpath)
1048                                                                 print "removed default storage link for offline device"
1049                                                         except OSError:
1050                                                                 pass
1051                         else:
1052                                 if uuid == old_default:
1053                                         cfg_uuid = config.storage.get(old_default, None)
1054                                         if cfg_uuid is not None and cfg_uuid["enabled"].value:
1055                                                 print self.getLinkPath(defaultpath), cfg_uuid["mountpoint"].value
1056                                                 if cfg_uuid["mountpoint"].value == self.getLinkPath(defaultpath):
1057                                                         try:
1058                                                                 unlink(defaultpath)
1059                                                                 print "removed default storage link for offline device"
1060                                                         except OSError:
1061                                                                 pass
1062
1063         def defaultStorageDeviceChanged(self, mountpoint = None):
1064                 part = self.getPartitionbyMountpoint(mountpoint)
1065                 if (part is not None and part in self.getConfiguredStorageDevices()):
1066                         config.storage_options.default_device.value = part.uuid
1067                 if (part is not None and part not in self.getConfiguredStorageDevices()):
1068                         config.storage_options.default_device.value = "<undefined>"
1069                 if (part is None and mountpoint == "<undefined>"):
1070                         config.storage_options.default_device.value = "<undefined>"
1071                 print "defaultStorageDeviceChanged:",config.storage_options.default_device.value
1072                 config.storage_options.default_device.save()
1073                 config.storage_options.save()
1074                 self.verifyDefaultStorageDevice()
1075
1076         def isConfiguredStorageDevice(self,uuid):
1077                 cfg_uuid = config.storage.get(uuid, None)
1078                 if cfg_uuid is not None and cfg_uuid["enabled"].value:
1079                         #print "isConfiguredStorageDevice:",uuid
1080                         return True
1081                 return False
1082
1083         def getdefaultStorageDevicebyUUID(self, uuid):
1084                 part = None
1085                 for p in self.getConfiguredStorageDevices():
1086                         if p.uuid == uuid:
1087                                 part = p
1088                 return part
1089
1090         def getConfiguredStorageDevices(self):
1091                 parts = [x for x in self.partitions if (x.uuid is not None and x.mounted() and self.isConfiguredStorageDevice(x.uuid))]
1092                 return [x for x in parts]
1093
1094         def getMountedPartitions(self, onlyhotplug = False):
1095                 parts = [x for x in self.partitions if (x.is_hotplug or not onlyhotplug) and x.mounted()]
1096                 devs = set([x.device for x in parts])
1097                 for devname in devs.copy():
1098                         if not devname:
1099                                 continue
1100                         dev, part = self.splitDeviceName(devname)
1101                         if part and dev in devs: # if this is a partition and we still have the wholedisk, remove wholedisk
1102                                 devs.remove(dev)
1103                 # return all devices which are not removed due to being a wholedisk when a partition exists
1104                 return [x for x in parts if not x.device or x.device in devs]
1105
1106         def splitDeviceName(self, devname):
1107                 # this works for: sdaX, hdaX, sr0 (which is in fact dev="sr0", part=""). It doesn't work for other names like mtdblock3, but they are blacklisted anyway.
1108                 dev = devname[:3]
1109                 part = devname[3:]
1110                 for p in part:
1111                         if not p.isdigit():
1112                                 return devname, 0
1113                 return dev, part and int(part) or 0
1114
1115         def getUserfriendlyDeviceName(self, dev, phys):
1116                 dev, part = self.splitDeviceName(dev)
1117                 description = "External Storage %s" % dev
1118                 have_model_descr = False
1119                 try:
1120                         description = readFile("/sys" + phys + "/model")
1121                         have_model_descr = True
1122                 except IOError, s:
1123                         print "couldn't read model: ", s
1124                 from Tools.HardwareInfo import HardwareInfo
1125                 if dev.find('sr') == 0 and dev[2].isdigit():
1126                         devicedb = DEVICEDB_SR
1127                 else:
1128                         devicedb = DEVICEDB
1129                 for physdevprefix, pdescription in devicedb.get(HardwareInfo().device_name,{}).items():
1130                         if phys.startswith(physdevprefix):
1131                                 if have_model_descr:
1132                                         description = pdescription + ' - ' + description
1133                                 else:
1134                                         description = pdescription
1135                 # not wholedisk and not partition 1
1136                 if part and part != 1:
1137                         description += " (Partition %d)" % part
1138                 return description
1139
1140         def addMountedPartition(self, device, desc):
1141                 already_mounted = False
1142                 for x in self.partitions[:]:
1143                         if x.mountpoint == device:
1144                                 already_mounted = True
1145                 if not already_mounted:
1146                         self.partitions.append(Partition(mountpoint = device, description = desc))
1147
1148         def removeMountedPartition(self, mountpoint):
1149                 for x in self.partitions[:]:
1150                         if x.mountpoint == mountpoint:
1151                                 self.partitions.remove(x)
1152                                 self.on_partition_list_change("remove", x)
1153
1154         def removeMountedPartitionbyDevice(self, device):
1155                 p = self.getPartitionbyDevice(device)
1156                 if p is not None:
1157                         #print "[removeMountedPartitionbyDevice] '%s', '%s', '%s', '%s', '%s'" % (p.mountpoint,p.description,p.device,p.force_mounted,p.uuid)
1158                         self.partitions.remove(p)
1159                         self.on_partition_list_change("remove", p)
1160
1161         def trigger_udev(self):
1162                 # We have to trigger udev to rescan sysfs 
1163                 cmd = "udevadm trigger"
1164                 res = system(cmd)
1165                 return (res >> 8)
1166
1167         def getPartitionbyDevice(self, dev):
1168                 for x in self.partitions[:]:
1169                         if x.device == dev:
1170                                 #print "[getPartitionbyDevice] '%s', '%s', '%s', '%s', '%s'" % (x.mountpoint,x.description,x.device,x.force_mounted,x.uuid)
1171                                 return x
1172                 return None
1173
1174         def getPartitionbyMountpoint(self, mountpoint):
1175                 for x in self.partitions[:]:
1176                         if x.mountpoint == mountpoint:
1177                                 #print "[getPartitionbyMountpoint] '%s', '%s', '%s', '%s', '%s'" % (x.mountpoint,x.description,x.device,x.force_mounted,x.uuid)
1178                                 return x
1179                 return None
1180
1181         def getDeviceNamebyUUID(self, uuid):
1182                 if path.exists("/dev/disk/by-uuid/" + uuid):
1183                         return path.basename(path.realpath("/dev/disk/by-uuid/" + uuid))
1184                 return None
1185
1186         def getPartitionUUID(self, part):
1187                 if not path.exists("/dev/disk/by-uuid"):
1188                         return None
1189                 for uuid in listdir("/dev/disk/by-uuid/"):
1190                         if not path.exists("/dev/disk/by-uuid/" + uuid):
1191                                 return None                     
1192                         if path.basename(path.realpath("/dev/disk/by-uuid/" + uuid)) == part:
1193                                 #print "[getPartitionUUID] '%s' - '%s'" % (uuid, path.basename(path.realpath("/dev/disk/by-uuid/" + uuid)) )
1194                                 return uuid
1195                 return None
1196
1197         def reloadExports(self):
1198                 if path.exists("/etc/exports") and path.exists("/usr/sbin/exportfs"):
1199                         Console().ePopen(("exportfs -r"))
1200
1201         def unmountPartitionbyMountpoint(self, mountpoint, device = None):
1202                 if path.exists(mountpoint) and path.ismount(mountpoint):
1203                         part = self.getPartitionbyMountpoint(mountpoint)
1204                         if part is not None and part.uuid is not None:
1205                                 if part.uuid == config.storage_options.default_device.value:
1206                                         print part.uuid,config.storage_options.default_device.value
1207                                         if (path.exists("/media/hdd") and path.islink("/media/hdd") and self.getLinkPath("/media/hdd") == mountpoint):
1208                                                 try:
1209                                                         unlink("/media/hdd")
1210                                                         print "removed old default storage link"
1211                                                 except OSError:
1212                                                         pass                                    
1213                         cmd = "umount" + " " + mountpoint
1214                         print "[unmountPartitionbyMountpoint] %s:" % (mountpoint)
1215                         system(cmd)
1216                         if (device is not None and not path.ismount(mountpoint)):
1217                                 self.removeMountedPartitionbyDevice(device)
1218                         self.reloadExports()
1219
1220         def unmountPartitionbyUUID(self, uuid):
1221                 mountpoint = config.storage[uuid]['mountpoint'].value
1222                 if mountpoint != "":
1223                         if path.exists(mountpoint) and path.ismount(mountpoint):
1224                                 partitionPath = "/dev/disk/by-uuid/" + uuid
1225                                 mountpoint = config.storage[uuid]['mountpoint'].value
1226                                 if (self.is_hard_mounted(partitionPath) and self.is_fstab_mountpoint(partitionPath, mountpoint) and self.get_fstab_mountstate(partitionPath, mountpoint) == 'auto'):
1227                                         print "[unmountPartitionbyUUID] disabling external mounted config entry for %s:" % (mountpoint)
1228                                         config.storage[uuid]["enabled"].value = False
1229                                         config.storage.save()
1230                                 else:
1231                                         part = self.getPartitionbyMountpoint(mountpoint)
1232                                         if part is not None and part.uuid is not None:
1233                                                 if part.uuid == config.storage_options.default_device.value:
1234                                                         print part.uuid,config.storage_options.default_device.value
1235                                                         if (path.exists("/media/hdd") and path.islink("/media/hdd") and self.getLinkPath("/media/hdd") == mountpoint):
1236                                                                 try:
1237                                                                         unlink("/media/hdd")
1238                                                                         print "removed old default storage link"
1239                                                                 except OSError:
1240                                                                         pass                                    
1241                                         cmd = "umount" + " " + mountpoint
1242                                         print "[unmountPartitionbyUUID] %s:" % (mountpoint)
1243                                         system(cmd)
1244                                 self.reloadExports()
1245
1246         def mountPartitionbyUUID(self, uuid):
1247                 if path.exists("/dev/disk/by-uuid/" + uuid):
1248                         print "[mountPartitionbyUUID] for UUID:'%s'" % (uuid)
1249                         cfg_uuid = config.storage.get(uuid, None)
1250                         partitionPath = "/dev/disk/by-uuid/" + uuid
1251                         mountpoint = cfg_uuid['mountpoint'].value
1252                         dev = self.getDeviceNamebyUUID(uuid)
1253                         devicepath = "/dev/" + str(dev)
1254
1255                         if (self.is_hard_mounted(partitionPath) or self.is_hard_mounted(devicepath)):
1256                                 #print "[mountPartitionbyUUID] - found possible Fstab mounted device:",partitionPath, devicepath, dev
1257                                 if (self.is_fstab_mountpoint(partitionPath, mountpoint) and self.get_fstab_mountstate(partitionPath, mountpoint) == 'auto'):
1258                                         cfg_uuid["enabled"].value = False
1259                                         config.storage.save()
1260                                 if (self.is_fstab_mountpoint(devicepath, mountpoint) and self.get_fstab_mountstate(devicepath, mountpoint) == 'auto'):
1261                                         cfg_uuid["enabled"].value = False
1262                                         config.storage.save()   
1263
1264                         if cfg_uuid['enabled'].value:
1265                                 if mountpoint != "":
1266                                         if not path.exists(mountpoint):
1267                                                 try:
1268                                                         makedirs(mountpoint)
1269                                                 except OSError:
1270                                                         print "[mountPartitionbyUUID] could not create mountdir:",mountpoint
1271
1272                                         if path.exists(mountpoint) and not path.ismount(mountpoint):
1273                                                 cmd = "mount -t auto /dev/disk/by-uuid/" + uuid + " " + mountpoint
1274                                                 system(cmd)
1275                                                 print "[mountPartitionbyUUID]:",cmd
1276
1277                                         hdd = self.getHDD(dev)
1278                                         if hdd is not None:
1279                                                 partitionType = self.getBlkidPartitionType(devicepath)
1280                                                 if partitionType is not None and partitionType in ( "ext2", "ext3" ):
1281                                                         moviedir = mountpoint + "/movie"
1282                                                         if not path.exists(moviedir):
1283                                                                 try:
1284                                                                         makedirs(moviedir)
1285                                                                 except OSError:
1286                                                                         print "[mountPartitionbyUUID] could not create moviedir:",moviedir
1287
1288                                         if path.ismount(mountpoint):
1289                                                 dev = self.getDeviceNamebyUUID(uuid)
1290                                                 if dev is not None:
1291                                                         p = self.getPartitionbyMountpoint(mountpoint)
1292                                                         if p is not None:
1293                                                                 x = self.getPartitionbyDevice(dev)
1294                                                                 if x is not None and x.mountpoint.startswith('/autofs'):
1295                                                                         self.removeMountedPartitionbyDevice(dev)
1296                                                                 p.mountpoint = mountpoint
1297                                                                 p.uuid = uuid
1298                                                                 p.device = dev
1299                                                                 p.force_mounted = False
1300                                                         else:
1301                                                                 p = self.getPartitionbyDevice(dev)
1302                                                                 if p is not None:
1303                                                                         p.mountpoint = mountpoint
1304                                                                         p.uuid = uuid
1305                                                                         p.device = dev
1306                                                                         p.force_mounted = False
1307                                         else:
1308                                                 print "[mountPartitionbyUUID] could not mount mountdir:",mountpoint
1309                 else:
1310                         print "[mountPartitionbyUUID] failed for UUID:'%s'" % (uuid)
1311
1312         def storageDeviceChanged(self, uuid):
1313                 if config.storage[uuid]["enabled"].value:
1314                         self.mountPartitionbyUUID(uuid)
1315                 else:
1316                         self.unmountPartitionbyUUID(uuid)
1317
1318         def setupConfigEntries(self, initial_call = False, dev = None):
1319                 if initial_call and not dev:
1320                         for uuid in config.storage.stored_values:
1321                                 print "[setupConfigEntries] initial_call for stored uuid:",uuid,config.storage.stored_values[uuid]
1322                                 config.storage[uuid] = ConfigSubDict()
1323                                 config.storage[uuid]["enabled"] = ConfigYesNo(default = False)
1324                                 config.storage[uuid]["mountpoint"] = ConfigText(default = "", visible_width = 50, fixed_size = False)
1325                                 config.storage[uuid]["device_description"] = ConfigText(default = "", visible_width = 50, fixed_size = False)
1326                                 config.storage[uuid]["device_info"] = ConfigText(default = "", visible_width = 50, fixed_size = False)
1327                                 config.storage[uuid]["isRemovable"] = ConfigBoolean(default = False)
1328                                 dev = self.getDeviceNamebyUUID(uuid)
1329                                 if dev is not None:
1330                                         p = self.getPartitionbyDevice(dev) or self.getPartitionbyMountpoint(config.storage[uuid]["mountpoint"].value)
1331                                         if p is None: # manually add partition entry
1332                                                 physdev = path.realpath('/sys/block/' + dev[:3] + '/device')[4:]
1333                                                 description = self.getUserfriendlyDeviceName(dev[:3], physdev)
1334                                                 p = Partition(mountpoint = config.storage[uuid]["mountpoint"].value, description = description, force_mounted = False, device = dev)
1335                                                 p.uuid = uuid
1336                                                 self.partitions.append(p)
1337                                                 self.on_partition_list_change("add", p) 
1338                                 if path.exists("/dev/disk/by-uuid/" + uuid):
1339                                         self.storageDeviceChanged(uuid)
1340                 if dev is not None:
1341                         uuid = self.getPartitionUUID(dev)
1342                         if uuid is not None:
1343                                 if config.storage.get(uuid, None) is None: #new unconfigured device added
1344                                         print "[setupConfigEntries] new device add for '%s' with uuid:'%s'" % (dev, uuid)
1345                                         hdd = self.getHDD(dev)
1346                                         if hdd is not None:
1347                                                 hdd_description = hdd.model()
1348                                                 cap = hdd.capacity()
1349                                                 if cap != "":
1350                                                         hdd_description += " (" + cap + ")"
1351                                                 device_info =  hdd.bus_description()
1352                                         else:
1353                                                 device_info = dev
1354                                                 hdd_description = "External Storage"
1355                                         config.storage[uuid] = ConfigSubDict()
1356                                         config.storage[uuid]["enabled"] = ConfigYesNo(default = False)
1357                                         config.storage[uuid]["mountpoint"] = ConfigText(default = "", visible_width = 50, fixed_size = False)
1358                                         config.storage[uuid]["device_description"] = ConfigText(default = "", visible_width = 50, fixed_size = False)
1359                                         config.storage[uuid]["device_info"] = ConfigText(default = "", visible_width = 50, fixed_size = False)
1360                                         config.storage[uuid]["isRemovable"] = ConfigBoolean(default = False)
1361                                         config.storage[uuid]["device_description"].setValue(hdd_description)
1362                                         config.storage[uuid]["device_info"].setValue(device_info)
1363                                         removable = False
1364                                         if hdd is not None:
1365                                                 removable = hdd.isRemovable
1366                                         config.storage[uuid]["isRemovable"].setValue(removable)                                 
1367                                         p = self.getPartitionbyDevice(dev)
1368                                         if p is None: # manually add partition entry (e.g. on long spinup times)
1369                                                 physdev = path.realpath('/sys/block/' + dev[:3] + '/device')[4:]
1370                                                 description = self.getUserfriendlyDeviceName(dev[:3], physdev)
1371                                                 p = Partition(mountpoint = self.getAutofsMountpoint(dev), description = description, force_mounted = True, device = dev)
1372                                                 p.uuid = uuid
1373                                                 self.partitions.append(p)
1374                                                 self.on_partition_list_change("add", p) 
1375                                         self.storageDeviceChanged(uuid)         
1376                                 else:
1377                                         print "[setupConfigEntries] new device add for '%s' with uuid:'%s'" % (dev, uuid)
1378                                         self.storageDeviceChanged(uuid)
1379                         else:
1380                                 "[setupConfigEntries] device add for '%s' without uuid !!!" % (dev)
1381
1382 harddiskmanager = HarddiskManager()