#!/usr/bin/python3

from time import sleep

import pydbus

_bus = pydbus.SystemBus()
_manager_if = _bus.get('org.freedesktop.UDisks2', 'Manager')

class iPodFilesystem:
	def __init__(self, fs, unmount_on_exit: bool|None=None):
		self.fs = fs
		self.was_mounted = len(self.fs.MountPoints) != 0
		self.unmount_on_exit = unmount_on_exit

	def __del__(self):
		if self.unmount_on_exit is True or (self.unmount_on_exit is None and not self.was_mounted):
			self.unmount()

	def mount(self):
		mountpoints = self.fs.MountPoints
		if len(mountpoints) == 0:
			print('Mounting iPod...')
			mnt = self.fs.Mount([])
			print('Mounted iPod.')
			return mnt
		else:
			print('iPod is already mounted.')
			return ''.join([chr(byte) for byte in self.fs.MountPoints[0]][:-1])

	def unmount(self):
		print('Unmounting iPod...')
		i=3
		while i > 0:
			try:
				self.fs.Unmount([])
			except:
				i-=1
				sleep(1)
		print('Unmounted iPod.')

def get_default_ipod():
	for block in _manager_if.GetBlockDevices([]):
		block_if = _bus.get('org.freedesktop.UDisks2', block)
		drive = block_if.Drive
		if drive == '/':continue
		drive_if = _bus.get('org.freedesktop.UDisks2', drive)

		try:
			fs_if = block_if['org.freedesktop.UDisks2.Filesystem']
		except:continue
		if drive_if.Vendor == 'Apple' and drive_if.Model == 'iPod':
			return iPodFilesystem(fs_if)
	return None