#!/usr/bin/python3
# -*- coding: utf-8 -*-

"""
iDevice mounter

This program scans, mounts and unmounts iPhones and iPads.

Author: Timothy E. Harris <maintainer@mxrepo.com>
Last edited: October 2017
License GPL-2+
"""

import sys, time, os
import subprocess

import gettext
gettext.bindtextdomain('idevice-mounter', '/usr/share/locale')
gettext.textdomain('idevice-mounter')
_ = gettext.gettext
gettext.install('idevice-mounter')

from PyQt5.QtWidgets import QMainWindow, QApplication, QLabel, QPushButton, QWidget, QMessageBox
from PyQt5.QtGui import QIcon, QPixmap
from PyQt5.QtCore import QCoreApplication

class Idevmanager(QMainWindow):
    
    def __init__(self):
        super().__init__()
        
        self.initUI()
        self.getDeviceinfo()    

    def getDeviceinfo(self):
        self.uid = str(os.getuid())
        p = subprocess.check_output(['/usr/bin/ideviceinfo -s -k DeviceName; exit 0'], shell=True)
        self.devicename = p.decode('utf-8').rstrip()
        if self.devicename == 'No device found, is it plugged in?':
           self.deviceid = ''
           self.mountb.setEnabled(False)
           self.umountb.setEnabled(False)
        else:
           p = subprocess.check_output(['/usr/bin/ideviceinfo -s -k UniqueDeviceID; exit 0'], shell=True)
           self.deviceid = p.decode('utf-8').rstrip()
           self.mypath = "/run/user/" + self.uid + "/" + self.deviceid + "/" + self.devicename
           if self.isMount():
              self.mountb.setEnabled(False)
              self.umountb.setEnabled(True)
           else:
              self.mountb.setEnabled(True)
              self.umountb.setEnabled(False)              
        self.label2.setText(self.devicename)
        self.label4.setText(self.deviceid)

    def mountDevice(self):
        if self.deviceid == '':
           self.mountb.setEnabled(False)
        else:
           self.mypath = "/run/user/" + self.uid + "/" +self.deviceid + "/" + self.devicename
           p = subprocess.call(["/bin/mkdir", "-p", self.mypath])
           p = subprocess.call(["/usr/bin/ifuse", "-u", self.deviceid, self.mypath])

        if self.isMount():
           thunar = subprocess.Popen(["/usr/bin/thunar", self.mypath])
           tpid = thunar.pid
           print(tpid)
           self.umountb.setEnabled(True)
           self.mountb.setEnabled(False)
           self.hide()
           os.waitpid(tpid, 0)
           self.show()
        else:
           self.umountb.setEnabled(False)
           self.mountb.setEnabled(True)

    def umountDevice(self):
        self.mypath = "/run/user/" + self.uid + "/" +self.deviceid + "/" + self.devicename
        if self.isMount():
           p = subprocess.call(["/bin/fusermount", "-u", self.mypath])
           p = subprocess.call(["/bin/rmdir", self.mypath])
           p = subprocess.call(["/bin/rmdir","/run/user/" + self.uid + "/" + self.deviceid ])
        self.umountb.setEnabled(False)
        self.mountb.setEnabled(True)

    def isMount(self):
        cmd = 'mount | grep "' + self.mypath + '"'
        p = subprocess.call([cmd], shell=True)
        if p == 0:
           return True
        else:
           return False

    def displayAbout(self):
        p = subprocess.check_output(['dpkg -l idevice-mounter | grep mounter | cut -f 4 -d " "' ], shell=True)
        myversion = p.decode('utf-8').rstrip()
        t1 = _("iDevice Mounter")
        t2 = _("Version:")
        t3 = _("GUI program for mounting & unmounting <br> iPhones and Ipads")
        t4 = _( "Copyright (c) MX Linux")       
        aboutBox = QMessageBox()
        aboutBox.setText("<p align=center><b><h2>" + t1 + "</h2></b></p><p align=center>" + t2 + " " + myversion + "</p><p align=center><h3>" +
                   t3 + "</h3></p><p align=center><a href=http://mxlinux.org>http://mxlinux.org</a> \
                   <br></p><p align=center>" + t4 + "<br /><br /></p>")
        aboutBox.addButton("Cancel", QMessageBox.YesRole)
        aboutBox.addButton("License", QMessageBox.NoRole)
        reply = aboutBox.exec_()
        if reply == 1:
           p=subprocess.call(["/usr/bin/antix-viewer", "/usr/share/doc/idevice-mounter/license.html", "iDevice Mounter license"])

    def displayHelp(self):
        p=subprocess.call(["/usr/bin/antix-viewer", "https://mxlinux.org/wiki/help-files/help-mx-idevice-mounter", "MX iDevice Mounter Help"])

    def initUI(self):               
        
        self.setGeometry(100, 300, 570, 360)
        self.setWindowTitle('Mount iDevice')
        self.setWindowIcon(QIcon('/usr/share/pixmaps/idevice.svg'))
        self.setStyleSheet("color: black")

        abouticon = QIcon.fromTheme('help-about')
        helpicon = QIcon.fromTheme('help-contents')
        closeicon = QIcon.fromTheme('window-close')
        umounticon = QIcon.fromTheme('application-x-apple-diskimage')
        mounticon = QIcon.fromTheme('folder-apple')
        scanicon = QIcon.fromTheme('drive-harddisk-usb-symbolic')

        self.mountb = QPushButton(_('Mount'), self)
        self.mountb.move(460, 120)
        self.mountb.setIcon(mounticon)
        self.mountb.clicked.connect(self.mountDevice)

        rescanb = QPushButton(_('Rescan'), self)
        rescanb.move(460, 50)
        rescanb.setIcon(scanicon)
        rescanb.clicked.connect(self.getDeviceinfo)

        self.umountb = QPushButton(_('Unmount'), self)
        self.umountb.move(460, 190)
        self.umountb.setIcon(umounticon)
        self.umountb.clicked.connect(self.umountDevice)

        self.closeb = QPushButton(_('Close'), self)
        self.closeb.move(460, 315)
        self.closeb.setIcon(closeicon)
        self.closeb.clicked.connect(QCoreApplication.instance().quit)

        self.aboutb = QPushButton(_('About'), self)
        self.aboutb.move(10, 315)
        self.aboutb.setIcon(abouticon)
        self.aboutb.clicked.connect(self.displayAbout)

        self.helpb = QPushButton(_('Help'), self)
        self.helpb.move(120, 315)
        self.helpb.setIcon(helpicon)
        self.helpb.clicked.connect(self.displayHelp)

        self.header = QLabel('', self)
        self.header.setGeometry(10, 10, 440, 60)
        tl1 = _("If your device is not found, make sure it is unlocked.")
        tl2 = _('If you get a  "Trust This Computer?"  popup on your device when you plug it in, answer "Trust", then Rescan.')
        self.header.setText(tl1 + "\n" + tl2)
        self.header.setWordWrap(True)
        
        self.header2 = QLabel('', self)
        self.header2.setGeometry(10, 60, 440, 90)
        self.header2.setText(_('If the information below describes your Apple device press the "Mount" button to access its files.'))
        self.header2.setWordWrap(True)
        
        self.label1 = QLabel("iName:", self)
        self.label1.setGeometry(10, 135, 50, 25)

        self.label2 = QLabel('', self)
        self.label2.setGeometry(70, 135, 340, 25)
        self.label2.setStyleSheet("background-color: lightyellow; border-style: outset; border-width: 2px; border-color: black")
        
        self.label3 = QLabel("UUID:", self)
        self.label3.setGeometry(10, 165, 60, 25)
         
        self.label4 = QLabel('', self)
        self.label4.setGeometry(70, 165, 340, 25)
        self.label4.setStyleSheet("background-color: lightyellow; border-style: outset; border-width: 2px; border-color: black")

        self.footer = QLabel('', self)
        self.footer.setGeometry(10, 190, 400, 100)
        self.footer.setText(_('Use the Unmount button before you remove your device.  If you have already unplugged it, plug your device back in, Rescan, and Unmount.'))
        self.footer.setWordWrap(True)
        
        self.mxlogo = QLabel(self)
        pixmap = QPixmap('/usr/share/mx-tweak/icons/logo.png')
        pixmap2 = pixmap.scaledToWidth(32)
        self.mxlogo.setPixmap(pixmap2)
        self.mxlogo.setGeometry(260, 320, 32, 32)

        self.show()

if __name__ == '__main__':
    
    app = QApplication(sys.argv)

    ex = Idevmanager()
    sys.exit(app.exec_())
