3
[I`                 @   s   d dl Z d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlmZm	Z	 ddl
mZ ddlmZ yd dlmZ W n$ ek
r   G dd deZY nX G d	d
 d
eZdS )    N)PIPEPopen   )get_arch)gettext)PluginManagerc               @   s   e Zd Zdd Zdd ZdS )r   c             O   s   d S )N )selfargskwsr   r   ?/usr/lib/python3/dist-packages/DistUpgrade/DistUpgradeQuirks.py__init__(   s    zPluginManager.__init__c             O   s   g S )Nr   )r	   r
   r   r   r   r   get_plugins+   s    zPluginManager.get_pluginsN)__name__
__module____qualname__r   r   r   r   r   r   r   '   s   r   c               @   s  e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	dd Z
dd Zdd Zdd Zdd Zdd Zdd Zdd Zd`dd Zd!d" Zd#d$ Zd%d& Zd'd( Zd)d* Zd+d, Zd-d. Zd/d0 Zd1d2 Zd3d4 Zd5d6 Zd7d8 Zd9d: Zd;d< Z d=d> Z!d?d@ Z"dAdB Z#dCdD Z$dEdF Z%dadHdIZ&dbdKdLZ'dMdN Z(dOdP Z)dQdR Z*dcdTdUZ+dVdW Z,dXdY Z-dZd[ Z.d\d] Z/d^d_ Z0dJS )dDistUpgradeQuirksz
    This class collects the various quirks handlers that can
    be hooked into to fix/work around issues that the individual
    releases have
    c             C   s   || _ |j| _|| _tddgtddj d j | _t | _	t
| j dg| _d| _d | _d| _i | _d| _d | _d | _d | _d S )	Nunamez-rT)stdoutuniversal_newlinesr   z	./plugins F)
controller_viewconfigr   r   communicatestripr   r   archr   plugin_managerextra_snap_space_poke_uid	_user_env_snapstore_reachable
_snap_list_from_version_to_version)r	   r   r   r   r   r   r   6   s    
zDistUpgradeQuirks.__init__c             C   s   | j jrtjd dS | jjdd}| jjdd}xN|d||f d||f gD ]0}x*| jj|D ]}tjd|  |j	  q`W qNW d	| }t
| |d}|dk	rtjd
|  |  d||f }t
| |d}|dk	rtjd
|  |  d||f }t
| |d}|dk	rtjd
|  |  dS )a  
        Run the specific quirks handler, the follow handlers are supported:
        - PreCacheOpen: run *before* the apt cache is opened the first time
                        to set options that affect the cache
        - PostInitialUpdate: run *before* the sources.list is rewritten but
                             after an initial apt-get update
        - PostDistUpgradeCache: run *after* the dist-upgrade was calculated
                                in the cache
        - StartUpgrade: before the first package gets installed (but the
                        download is finished)
        - PostUpgrade: run *after* the upgrade is finished successfully and
                       packages got installed
        - PostCleanup: run *after* the cleanup (orphaned etc) is finished
        z)not running quirks in partialUpgrade modeNZSourcesZToZFromz%s%sz	from_%s%szrunning quirks plugin %sz%szquirks: running %s)r   Z_partialUpgradelogginginfor   getr   r   debugZdo_cleanup_cruftgetattr)r	   Z
quirksNameZ
to_releaseZfrom_releaseZ	conditionZpluginfuncnamefuncr   r   r   runK   s6    


zDistUpgradeQuirks.runc             C   s   t jd dS )z3 run before the apt cache is opened the first time zrunning Quirks.PreCacheOpenN)r&   r)   )r	   r   r   r   PreCacheOpen   s    zDistUpgradeQuirks.PreCacheOpenc             C   s^   t jd | j  | jj}| j| d|kr:t jd dS |d jrL| j  | jrZ| j	  dS )z2 run after the apt cache is opened the first time z&running Quirks.bionicPostInitialUpdatesnapdz'package required for Quirk not in cacheN)
r&   r)   _get_from_and_to_versionr   cache_test_and_warn_if_ros_installedis_installed_checkStoreConnectivityr"   _calculateSnapSizeRequirements)r	   r1   r   r   r   bionicPostInitialUpdate   s    



z)DistUpgradeQuirks.bionicPostInitialUpdatec             C   sD   t jd | jj}d|kr(t jd d S |d jr@| jr@| j  d S )Nz running Quirks.bionicPostUpgrader/   z'package required for Quirk not in cache)r&   r)   r   r1   r3   r"   _replaceDebsAndSnaps)r	   r1   r   r   r   bionicPostUpgrade   s    


z#DistUpgradeQuirks.bionicPostUpgradec             C   s   t jd dS )z run after cleanup zrunning Quirks.PostCleanupN)r&   r)   )r	   r   r   r   PostCleanup   s    zDistUpgradeQuirks.PostCleanupc             C   sN   t jd | j  | j  | j  | j  | j  | j  | j  | j	  d S )Nzrunning Quirks.StartUpgrade)
r&   r)   _applyPatches_removeOldApportCrashes_killUpdateNotifier_killKBluetooth_killScreensaver_pokeScreensaver_inhibitIdle_stopDocvertConverter)r	   r   r   r   StartUpgrade   s    
zDistUpgradeQuirks.StartUpgradec             C   s   t jd | j  dS )z( run after calculating the dist-upgrade z#running Quirks.PostDistUpgradeCacheN)r&   r)   _install_linux_metapackage)r	   r   r   r   PostDistUpgradeCache   s    
z&DistUpgradeQuirks.PostDistUpgradeCachec             C   sl   t  }ytjddgtjdd}W n tk
r4   |S X x0|j d jdD ]}|rJ|j|j d  qJW |S )z8 return a set of pci ids of the system (using lspci -n) lspciz-nT)r   r   r   
   )set
subprocessr   r   OSErrorr   splitadd)r	   rE   pliner   r   r   _get_pci_ids   s    zDistUpgradeQuirks._get_pci_idsc             C   s   d| _ d| _d S )Nz16.04z18.04)r$   r%   )r	   r   r   r   r0      s    z*DistUpgradeQuirks._get_from_and_to_versionc             C   s   d}t jj| sdt jkr d S tjdddgtt jdd}|dkrRtj	d	 d S tj|g}tj	d
||f  |dkr| j
jtdtd}|s| jj  d S )Nz/usr/lib/nux/unity_support_testDISPLAYZpsz-Czunity-panel-servicew)r   r   z5_test_and_warn_for_unity_3d_support: no unity runningz6_test_and_warn_for_unity_3d_support '%s' returned '%s'zBYour graphics hardware may not be fully supported in Ubuntu 14.04.aS  Running the 'unity' desktop environment is not fully supported by your graphics hardware. You will maybe end up in a very slow environment after the upgrade. Our advice is to keep the LTS version for now. For more information see https://wiki.ubuntu.com/X/Bugs/UpdateManagerWarningForUnity3D Do you still want to continue with the upgrade?)ospathexistsenvironrI   callopendevnullr&   r)   r   askYesNoQuestion_r   abort)r	   ZUNITY_SUPPORT_TESTZreturn_coderesr   r   r   #_test_and_warn_for_unity_3d_support   s(    

	z5DistUpgradeQuirks._test_and_warn_for_unity_3d_supportc             C   sP   dddddddg}| j  }t|j|rL| jjtdtd	}|sL| jj  d S )
Nz	8086:7121z	8086:7125z	8086:1132z	8086:3577z	8086:2562z	8086:3582z	8086:2572zFYour graphics hardware may not be fully supported in Ubuntu 12.04 LTS.zThe support in Ubuntu 12.04 LTS for your Intel graphics hardware is limited and you may encounter problems after the upgrade. For more information see https://wiki.ubuntu.com/X/Bugs/UpdateManagerWarningForI8xx Do you want to continue with the upgrade?)rO   rH   intersectionr   rY   rZ   r   r[   )r	   ZI8XX_PCI_IDSrE   r\   r   r   r   _test_and_warn_on_i8xx   s    
z(DistUpgradeQuirks._test_and_warn_on_i8xxc             C   s   | j dr| jd r| jjtdtd}|s:| jj  dddddd	g}tjd
dj	|  | jj
jdd}x|D ]}|j| qtW | jj
jdddj	| dS )zi
        Some cards are no longer supported by fglrx. Check if that
        is the case and warn
        ZfglrxzhUpgrading may reduce desktop effects, and performance in games and other graphically intensive programs.zThis computer is currently using the AMD 'fglrx' graphics driver. No version of this driver is available that works with your hardware in Ubuntu 10.04 LTS.

Do you want to continue?zxorg-driver-fglrxzxorg-driver-fglrx-envyzfglrx-kernel-sourcezfglrx-amdccclezxorg-driver-fglrx-devZlibamdxvba1z	remove %sz, ZDistroZPostUpgradePurge,N)_checkVideoDriver_supportInModaliasesr   rY   rZ   r   r[   r&   r)   joinr   ZgetlistappendrH   )r	   r\   ZremovalsZpostupgradepurgeremover   r   r   '_test_and_warn_on_dropped_fglrx_support  s*    



z9DistUpgradeQuirks._test_and_warn_on_dropped_fglrx_supportc             C   sR   | j dkrNtjd | j sNtjd td}td}| jj|| | jj  dS )z
        Test and fail if the cpu is not i686 or more or if its a newer
        CPU but does not have the cmov feature (LP: #587186)
        i386zchecking for i586 CPUznot a i686 or no cmovzNo i686 CPUzYour system uses an i586 CPU or a CPU that does not have the 'cmov' extension. All packages were built with optimizations requiring i686 as the minimal architecture. It is not possible to upgrade your system to a new Ubuntu release with this hardware.N)	r   r&   r)   _cpu_is_i686_and_has_cmoverrorrZ   r   r   r[   )r	   summarymsgr   r   r   _test_and_fail_on_non_i686/  s    


z,DistUpgradeQuirks._test_and_fail_on_non_i686/proc/cpuinfoc             C   s   t jj|stjd|  dS t|}|j }W d Q R X tjd|tj	rXtj
d dS tjd|tj	}|rd|jdj krtj
d	|jd  tj
d
 dS dS )Nzcannot open %s ?!?Tz^cpu family\s*:\s*[345]\s*z found cpu family [345], no i686+Fz^flags\s*:\s*(.*)Zcmovr   zfound flags '%s'zcan not find cmov in flags)rR   rS   rT   r&   ri   rW   readresearch	MULTILINEr)   grouprK   )r	   Zcpuinfo_pathfcpuinfomatchr   r   r   rh   D  s    


z+DistUpgradeQuirks._cpu_is_i686_and_has_cmovc             C   s6   | j dkr2| j s2| jjtdtd | jj  dS )z~
        Test and fail if the cpu is not a arm v6 or greater,
        from 9.10 on we do no longer support those CPUs
        ZarmelzNo ARMv6 CPUzYour system uses an ARM CPU that is older than the ARMv6 architecture. All packages in karmic were built with optimizations requiring ARMv6 as the minimal architecture. It is not possible to upgrade your system to a new Ubuntu release with this hardware.N)r   _checkArmCPUr   ri   rZ   r   r[   )r	   r   r   r   _test_and_fail_on_non_arm_v6W  s    

z.DistUpgradeQuirks._test_and_fail_on_non_arm_v6c             C   sb   yt jdd W nL tk
r\   tjd | jjtdtd}|sN| jj	  | jj
  Y nX dS )zd
        upstart and vserver environments are not a good match, warn
        if we find one
        r   r   zno init foundzNo init availablea  Your system appears to be a virtualised environment without an init daemon, e.g. Linux-VServer. Ubuntu 10.04 LTS cannot function within this type of environment, requiring an update to your virtual machine configuration first.

Are you sure you want to continue?N)rR   killrJ   r&   warningr   rY   rZ   r   r[   processEvents)r	   r\   r   r   r   _test_and_warn_if_vserveri  s    


z+DistUpgradeQuirks._test_and_warn_if_vserverc             C   s   t  }x dD ]}|jtjd|  qW d}x>|D ]6}|r<P x*|D ]"}|j|jrB|js^|jrbd}P qBW q2W |r| jj	t
d	t
d
}|s| jj  dS )z
        Test and warn if ROS is installed. A given ROS release only
        supports specific Ubuntu releases, and can cause the upgrade
        to fail in an overly-cryptic manner.
        catkinrosboost-cfgroscleanros-environmentros-workspacezros-[^\-]+-%sFTz-The Robot Operating System (ROS) is installeda	  It appears that ROS is currently installed. Each ROS release is very strict about the versions of Ubuntu it supports, and Ubuntu upgrades can fail if that guidance isn't followed. Before continuing, please either uninstall ROS, or ensure the ROS release you have installed supports the version of Ubuntu to which you're upgrading.

For ROS 1 releases, refer to REP 3:
https://www.ros.org/reps/rep-0003.html

For ROS 2 releases, refer to REP 2000:
https://www.ros.org/reps/rep-2000.html

Are you sure you want to continue?N)r|   r}   r~   r   r   )rH   rL   ro   compileru   namer3   marked_installr   rY   rZ   r   r[   )r	   r1   Zros_package_patternsZpackage_nameZros_is_installedpkgpatternr\   r   r   r   r2     s0        



z1DistUpgradeQuirks._test_and_warn_if_ros_installedc             C   sX   t jd tjjds$t jd dS td}|j }W dQ R X tj	d|tj
rTdS dS )zE
        parse /proc/cpuinfo and search for ARMv6 or greater
        zchecking for ARM CPU versionz/proc/cpuinfozcannot open /proc/cpuinfo ?!?FNz^Processor\s*:\s*ARMv[45]T)r&   r)   rR   rS   rT   ri   rW   rn   ro   rp   rq   )r	   rs   rt   r   r   r   rv     s    


zDistUpgradeQuirks._checkArmCPUc             C   s(   t jjdr$tjd tjddg dS )z, /etc/init.d/apparmor stop (see bug #559433)z/etc/init.d/apparmorz/etc/init.d/apparmor stopstopN)rR   rS   rT   r&   r)   rI   rV   )r	   r   r   r   _stopApparmor  s    
zDistUpgradeQuirks._stopApparmorc             C   s(   t jjdr$tjd tjddg dS )z5 /etc/init.d/docvert-converter stop (see bug #450569)z/etc/init.d/docvert-converterz"/etc/init.d/docvert-converter stopr   N)rR   rS   rT   r&   r)   rI   rV   )r	   r   r   r   rA     s    
z'DistUpgradeQuirks._stopDocvertConverterc             C   s*   t jjdr&tjd tjdddg dS )zkill update-notifierz/usr/bin/killallzkilling update-notifierkillallz-qzupdate-notifierN)rR   rS   rT   r&   r)   rI   rV   )r	   r   r   r   r<     s    
z%DistUpgradeQuirks._killUpdateNotifierc             C   s,   t jjdr(tjd tjddddg dS )z3killall kblueplugd kbluetooth (riddel requested it)z/usr/bin/killallzkilling kblueplugd kbluetooth4r   z-qZ
kblueplugdZkbluetooth4N)rR   rS   rT   r&   r)   rI   rV   )r	   r   r   r   r=     s    
z!DistUpgradeQuirks._killKBluetoothc             C   s*   t jjdr&tjd tjdddg dS )zkillall gnome-screensaver z/usr/bin/killallzkilling gnome-screensaverr   z-qzgnome-screensaverN)rR   rS   rT   r&   r)   rI   rV   )r	   r   r   r   r>     s    
z"DistUpgradeQuirks._killScreensaverc             C   s~   t jjdrzt jjdrztjd d}|d7 }|d7 }y tj|dd| _	t
j| j W n" ttfk
rx   tjd	 Y nX d S )
Nz/usr/bin/xdg-screensaverrP   z#setup poke timer for the scrensaverzwhile true;z3 do /usr/bin/xdg-screensaver reset >/dev/null 2>&1;z sleep 30; doneT)shellz failed to setup screensaver poke)rR   rS   rT   rU   r(   r&   r)   rI   r   r   atexitregister_stopPokeScreensaverrJ   
ValueError	exception)r	   cmdr   r   r   r?     s    
z"DistUpgradeQuirks._pokeScreensaverc             C   s   yt jdd| jdg}|j jdd }td| d d}|j jd	}W d Q R X x2|D ]*}t|rZ|jd
d}|d | j|d < qZW W nD t j	k
r } z&|j
dkrtjd n
tjd W Y d d }~X nX d S )NZpgrepz-uzgnome-sessionrF   r   z/proc/z/environr =r   z"gnome-session not running for userzfailed to read user env)rI   Zcheck_outputr    decoderK   rW   rn   lenr!   CalledProcessError
returncoder&   r)   r   )r	   pidrs   datarN   enver   r   r   _getUserEnv  s    

zDistUpgradeQuirks._getUserEnvc             C   s(  t jjdr$t jjdd| _| js4t jjdd| _| jsRtjd tjd d S | j	  | j
sdd S t jt| j tjd yr| j
jdd}|stjd	 tjd d S |jd
}tjddddg| j
d}x |D ]}d|krtj|j qW W n$ ttfk
r   tjd Y nX t jt j  d S )Nz/usr/bin/gnome-session-inhibitZSUDO_UIDr   Z
PKEXEC_UIDz"failed to determine user upgradingz$failed to inhibit gnome-session idlezinhibit gnome-session idleZXDG_CURRENT_DESKTOPz"failed to find XDG_CURRENT_DESKTOP:zgnome-session-inhibitz	--inhibitidlez--inhibit-only)r   ZGNOME)rR   rS   rT   rU   r(   r    r&   r)   ri   r   r!   seteuidintrK   rI   r   r   r   	terminaterJ   r   r   getuid)r	   Zxdg_desktopr   Zdesktopr   r   r   r@     s:    







zDistUpgradeQuirks._inhibitIdlec             C   sP   d}| j d k	rLy| j j  | j j }W n tk
rD   tjd Y nX d | _ |S )NFzfailed to stop screensaver poke)r   r   waitrJ   r&   r   )r	   r\   r   r   r   r     s    

z&DistUpgradeQuirks._stopPokeScreensaverc             C   s|   yFx@dD ]8}x2t j d| D ] }tjd||f  tj| qW qW W n0 tk
rv } ztjd|  W Y dd}~X nX dS )	z: remove old apport crash files and whoopsie control files .crash.upload	.uploadedz/var/crash/*%szremoving old %s file '%s'z+error during unlink of old crash files (%s)N)r   r   r   )globr&   r)   rR   unlink	Exceptionry   )r	   Zextrs   r   r   r   r   r;   (  s    
z)DistUpgradeQuirks._removeOldApportCrashesc             C   s   d}t jj }d|d< tdddgtt|ddj }tjd	|d
 tjrPd| _	dS tjd|d
 tjrt
jd | jjtdtd}nHd|d krt
jd | jjtdtd}nd|d krd}t
jd |s| jj  dS )z: check for connectivity to the snap store to install snapsFzC.UTF-8ZLANGsnapr)   ZconnectivityT)r   stderrr   r   z	^ \* PASSr   Nz^ \*.*unreachablezNo snap store connectivityzConnection to Snap Store failedzYour system does not have a connection to the Snap Store. For the best upgrade experience make sure that your system can connect to api.snapcraft.io.
Do you still want to continue with the upgrade?zerror: unknown commandr   z snap debug command not availablezOutdated snapd packagezYour system does not have the latest version of snapd. Please update the version of snapd on your system to improve the upgrade experience.
Do you still want to continue with the upgrade?zerror: access deniedzNot running as root!)rR   rU   copyr   r   r   ro   rp   rq   r"   r&   ri   r   rY   rZ   r   r[   )r	   r\   Zsnap_envZ	connectedr   r   r   r4   2  s0    



z)DistUpgradeQuirks._checkStoreConnectivityc             C   sR  dd l }dd l}ddlm} | j  | jjtd x| jj	 D ]\}}|d dkrZqBdd|d |d	 d
}g |gd}|j
jdt|j|ddd}|jdd |jdd |jd| j yN|j
j|j }	t|	tr|	jd}	|j|	}
t|
d d d d d }W n, t|tfk
r:   tjd|  wBY nX |  j|7  _qBW d S )Nr   )URLErrorz"Calculating snap size requirementscommandinstallzupgrade-size-checkZdownloadzsnap-idchannel)zinstance-keyactionzsnap-idr   )contextZactionsz)https://api.snapcraft.io/v2/snaps/refreshzutf-8)encoding)Zurlr   zSnap-Device-SeriesZ16zContent-typezapplication/jsonzSnap-Device-ArchitectureZresultsr   sizezFailed fetching size of snap %s)jsonZurllib.requestZurllib.errorr   _prepare_snap_replacement_datar   updateStatusrZ   r#   itemsZrequestZRequestbytesdumpsZ
add_headerr   Zurlopenrn   
isinstancer   loadsr   KeyErrorr   r&   r)   r   )r	   r   Zurllibr   r   snap_objectr   r   ZreqZresponser'   r   r   r   r   r5   X  s<    



 z0DistUpgradeQuirks._calculateSnapSizeRequirementsc             C   s  | j jtd ddlm} | }d| jj krJ| jd |d< | jjd d| jj krr| jd |d< | jjd x| jj D ]\}}|||< q~W x6|j D ](\}}|d }|dkr| j jtd|  d	|d
|d |g}nP|dkr
| j jtd|  d	||g}n&| j jtd|  d	|d
|d |g}y*| j j	  t
j|t
jdd}| j j	  W n, t
jk
r   tjd||f  wY nX |jdkrtjd||f  |dkr|d r| jjj|d  qW dS )z? install a snap and mark its corresponding package for removal zProcessing snap replacementsr   )OrderedDictzgnome-3-34-1804zgtk-common-themesr   refreshzrefreshing snap %sr   z	--channelr   re   zremoving snap %szinstalling snap %sT)r   Zcheckz%s of snap %s failedz%s of snap %s succeededr   debN)r   r   rZ   collectionsr   r#   keyspopr   rz   rI   r-   r   r   r&   r)   r   r   Zforced_obsoletesrd   )r	   r   Zordered_snap_listr   r   r   Z	popenargsprocr   r   r   r7     sJ    

z&DistUpgradeQuirks._replaceDebsAndSnapsc             C   sx   t jd d}td}|j }W dQ R X tjd|tjr>d}|stt jd td}td	}| j	j|| | j
j  dS )
z check PAE in /proc/cpuinfo 	_checkPaer   z/proc/cpuinfoNz^flags\s+:.* pae r   zno pae in /proc/cpuinfozPAE not enabledzYour system uses a CPU that does not have PAE enabled. Ubuntu only supports non-PAE systems up to Ubuntu 12.04. To upgrade to a later version of Ubuntu, you must enable PAE (if this is possible) see:
http://help.ubuntu.com/community/EnablingPAE)r&   r)   rW   rn   ro   rp   rq   ri   rZ   r   r   r[   )r	   Zpaers   rt   rj   rk   r   r   r   r     s    


zDistUpgradeQuirks._checkPaec             C   st   d}t jj|sdS t|}|j }W dQ R X x>|D ]6}|jdd j }|j jdr6|j	d| r6dS q6W dS )	z2 check if the given driver is in use in xorg.conf z/etc/X11/xorg.confFN#r   Zdriverz"%s"T)
rR   rS   rT   rW   	readlinesrK   r   lower
startswithendswith)r	   r   ZXORGrs   linesrN   sr   r   r   ra     s    

z#DistUpgradeQuirks._checkVideoDriver	./patchesc       
      C   sl  t jj|stjd dS xJt j|D ]:}d|krFtjd|  q(tjd|  |jdd\}}}|jdd}tjd	|||f  t jj|stjd
|  q(tj	 }t
|d}|j|j  W dQ R X |j |krtjd|  q(n|j |kr
tjd|  q(ddlm}	 y(|	|t jj||| tjd|  W q( tk
rb   tjd|  Y q(X q(W dS )z
        helper that applies the patches in patchdir. the format is
        _path_to_file.md5sum and it will apply the diff to that file if the
        md5sum matches
        zno patchdirN.zskipping '%s' (no '.')z'check if patch '%s' needs to be appliedrG   rZ   /ztarget for '%s' is '%s' -> '%s'ztarget '%s' does not existrbz%already at target hash, skipping '%s'z(unexpected target md5sum, skipping: '%s'r   )patchzapplied '%s' successfullyzed failed for '%s')rR   rS   rT   r&   r)   listdirrsplitreplacehashlibmd5rW   updatern   Z	hexdigestry   ZDistUpgradePatcherr   rc   r'   r   r   )
r	   Zpatchdirrs   Zencoded_pathZmd5sumZresult_md5sumrS   r   fdr   r   r   r   r:     s>    
zDistUpgradeQuirks._applyPatchesNc       	      C   s   |s| j  }|| jjks(| jj| j r6tjd dS | jj| }xn| j|jjD ]\\}}xR|D ]J}tj	d|}|r`d|j
d|j
df }|j |kr`tjd|  dS q`W qRW tjd	|  dS )
z
        Check if pkgname will work on this hardware

        This helper will check with the modaliasesdir if the given
        pkg will work on this hardware (or the hardware given
        via the lspci argument)
        zcan not find '%s' in cacheFzpci:v0000(.+)d0000(.+)sv.*z%s:%sr   rG   z%found system pciid '%s' in modaliasesTz4checking for %s support in modaliases but none found)rO   r   r1   	candidater&   ry   !_parse_modaliases_from_pkg_headerrecordro   ru   rr   r   r)   )	r	   ZpkgnamerE   r   moduleZ
pciid_listZpciidmZmatchidr   r   r   rb     s(    	

z&DistUpgradeQuirks._supportInModaliasesc             C   sh   d|krg S g }xR|d j dD ]@}|jd}|s4q |j d\}}|j|dd |j dD f q W |S )z. return a list of (module1, (pciid, ...), ...)Z
Modaliases)z, (c             S   s   g | ]}|j  qS r   )r   ).0xr   r   r   
<listcomp>-  s    zGDistUpgradeQuirks._parse_modaliases_from_pkg_header.<locals>.<listcomp>r`   )rK   r   rd   )r	   Z	pkgrecordmodulesr   r   Zpciidsr   r   r   r   "  s    
"z3DistUpgradeQuirks._parse_modaliases_from_pkg_headerc             C   s   t jd | jj}d|kr(t jd d S |d jp:|d jsJt jd d S yddd l}|jj }xL|D ]}d|j	krdt jd P qdW t j
d |jd	d
| jjdgd |j  W n tk
r   t jd Y nX d S )N_add_extras_repositoryzubuntu-extras-keyringz-no ubuntu-extras-keyring, no need to add repoz2ubuntu-extras-keyring not installed/marked_installr   zextras.ubuntu.comz*found extras.ubuntu.com, no need to add itz/no extras.ubuntu.com, adding it to sources.listr   zhttp://extras.ubuntu.com/ubuntumainz!Third party developers repositoryzerror adding extras.ubuntu.com)r&   r)   r   r1   r   Z	installedZaptsources.sourceslistZsourceslistZSourcesListZurir'   rL   ZtoDistZsaver   r   )r	   r1   Z
aptsourcesZsourcesentryr   r   r   r   0  s.    










z(DistUpgradeQuirks._add_extras_repositoryc             C   s`   y<| j j}d|kr:|d jr:d|kr:tjd |jdd W n tk
rZ   tjd Y nX dS )z foomatic-db-gutenprint get removed during the upgrade,
            replace it with the compressed ijsgutenprint-ppds
            (context is foomatic-db vs foomatic-db-compressed-ppds)
        zfoomatic-db-gutenprintzijsgutenprint-ppdszinstalling ijsgutenprint-ppdsz1foomatic-db-gutenprint -> ijsgutenprint-ppds rulez_gutenprint_fixup failedN)r   r1   Zmarked_deleter&   r'   mark_installr   r   )r	   r1   r   r   r   _gutenprint_fixupJ  s    


z#DistUpgradeQuirks._gutenprint_fixuprg   c             C   s\   d}t jj|sXyt jd W n tk
r2   Y nX t|d}|jd|  W dQ R X dS )z5 enable multiarch via /etc/dpkg/dpkg.cfg.d/multiarch z/etc/dpkg/dpkg.cfg.d/multiarchz/etc/dpkg/dpkg.cfg.d/rQ   zforeign-architecture %s
N)rR   rS   rT   makedirsrJ   rW   write)r	   Zforeign_archZcfgrs   r   r   r   _enable_multiarch[  s    z#DistUpgradeQuirks._enable_multiarchc             C   sv   t jd}|j|}|j|}|rRd|jd|jdf }d|jd|jdf }tjd||f  tjj||dkS )z# copied from ubuntu-drivers common z(.+)-([0-9]+)-(.+)z%s-%sr   rG   zComparing %s with %sr   )	ro   r   ru   rr   r&   r)   aptapt_pkgZversion_compare)r	   Zterm1Zterm2r   Zmatch1Zmatch2r   r   r   _is_greater_thanf  s    




z"DistUpgradeQuirks._is_greater_thanc             C   s   |rdp
d}t jd}t jd}d}d}x|D ]}d|jkr.d|jkr.|jsR|jr.|j|j}	|	r.|jjd }
d|	jd	|	jd
f }| j	||r.|}|j|
}d|
kr|rd||	jd|jd	f }q.d||	jdf }q.W |S )zb Get the linux headers or linux metapackage
            copied from ubuntu-drivers-common
        z-headersr   zlinux-image-(.+)-([0-9]+)-(.+)z
linux-(.+)zlinux-imageZextraZSourcez%s-%sr   rG   z-lts-zlinux%s-%s-%s   z
linux%s-%s)
ro   r   r   r3   r   ru   r   r   rr   r   )r	   r1   Zheaderssuffixr   Zsource_patternZmetapackageversionr   ru   sourceZcurrent_versionZmatch_sourcer   r   r   _get_linux_metapackagev  s4    




	z(DistUpgradeQuirks._get_linux_metapackagec             C   sZ   | j j}| j|d}||kr.tjd|  dS || jsVtjd|  d}|j|| dS )zo Ensure the linux metapackage is installed for the newest_kernel
            installed. (LP: #1509305)
        Fz$linux metapackage (%s) not availableNz installing linux metapackage: %sz8linux metapackage may have been accidentally uninstalled)r   r1   r   r&   r'   r3   r   )r	   r1   Zlinux_metapackagereasonr   r   r   rC     s    
z,DistUpgradeQuirks._install_linux_metapackagec             C   s@   | j js<tjjjds<d}|d7 }tj| tjjjdd dS )z] ensure that on a desktop install recommends are installed
            (LP: #759262)
        zApt::Install-Recommendsz%Apt::Install-Recommends was disabled,z! enabling it just for the upgrade1N)	r   Z
serverModer   r   r   Zfind_br&   ry   rH   )r	   rk   r   r   r   +ensure_recommends_are_installed_on_desktops  s    
z=DistUpgradeQuirks.ensure_recommends_are_installed_on_desktopsc             C   s  ddl }i | _d| j }d| j }i }i }y4tjjtjjt}t	|d d}|j
|}|j  x|d D ]t}	|d |	 }
|
jdd}|| jjkrql|r| jj| jdkrql|
jd	d}|
jd
|}|
jd|}|||f||	< qlW xx|d D ]l}	|d |	 }|jd	d}|jdd}|| jjkr&q|rB| jj| jdkrBq|jd
|}||f||	< qW W n2 tk
r } ztjd|  W Y dd}~X nX d}tjddgdtjdj }|rdd |d jddd- D }x6|D ].}	|	|ks|	|krqnd||f||	< qW | jjtd x6|j D ](\}	\}}}i }tjdd|	gdtjdj }| jj  tjd|d tjrtj d|	  tjd| |d tjstj d|	  q,d|d< n| jj}|r||ks|| j rtj d||	f  q,tjd |d }|s$tj d!|	  q,d"|d< ||d	< |j!d|d#< ||d$< || j|	< q,W xh|j D ]Z\}	\}}i }tjdd|	gdtjdj }| jj  tjd|d tjrftj d|	  tjd| |d tjstj d|	  qfd%|d< tjdd&|	gdtjdj }| jj  x|d jdD ]}|j }t"|d'krJq,|d }|d( }|j#|	d) r,|jd)d }|d*kr,||kr,tj d+|	|f  d|d< d,|d$< P q,W || j|	< qfW | jS ).z Helper function fetching all required info for the deb-to-snap
            migration: version strings for upgrade (from and to) and the list
            of snaps (with actions).
        r   Nzstable/ubuntu-%sz/deb2snap.jsonr   ZseededmetapkgFr   from_channel
to_channelZunseededz%error reading deb2snap.json file (%s)r   r   listT)r   r   c             S   s   g | ]}|j  d  qS )r   )rK   )r   rN   r   r   r   r     s   zDDistUpgradeQuirks._prepare_snap_replacement_data.<locals>.<listcomp>rF   r   zChecking for installed snapsr'   z^installed: zSnap %s is installedz^tracking:.*%sz+Snap %s is not tracking the release channelr   r   zFDeb package %s is not installed. Skipping snap package %s installationzsnap-id:\s*(\w*)z'Could not parse snap-id for the %s snapr   zsnap-idr   re   Zconnections   rG   r   -z9Snap %s is being used by %s. Switching it to stable trackZstable)$r   r#   r$   r%   rR   rS   dirnameabspath__file__rW   loadcloser(   r   r1   r3   r   r&   ry   rI   r   r   r   rK   r   r   rZ   r   rz   ro   rp   rq   r)   rr   r   r   )r	   r   r   r   Zseeded_snapsZunseeded_snapsZcurrent_pathZd2s_fileZd2sr   Zseedr   r   Z	from_chanZto_chanZunseedr   Z	snap_listZsnaps_installedr   Z	snap_infor1   ru   ZconnsZconnZ	conn_colsZplugZslotZ	plug_snapr   r   r   r     s    


 









z0DistUpgradeQuirks._prepare_snap_replacement_data)rm   )r   )N)rg   )1r   r   r   __doc__r   r-   r.   r6   r8   r9   rB   rD   rO   r0   r]   r_   rf   rl   rh   rw   r{   r2   rv   r   rA   r<   r=   r>   r?   r   r@   r   r;   r4   r5   r7   r   ra   r:   rb   r   r   r   r   r   r   rC   r   r   r   r   r   r   r   /   s\   5!)
/#
&*/
/

0r   )r   r   r   r&   rR   ro   r   rI   r   r   Zutilsr   ZDistUpgradeGettextr   rZ   Zjanitor.plugincore.managerr   ImportErrorobjectr   r   r   r   r   <module>   s   