#!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# «ubuntu-partition» - OEM Config plugin for Ubuntu-Recovery
#
# Copyright (C) 2012, Canonical, Ltd.
#
# Author:
#  - Christopher Townsend <Christopher.Townsend@canonical.com>
#
# This is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2 of the License, or at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this application; if not, write to the Free Software Foundation, Inc.,
# 51
# Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
##################################################################################

import os
import subprocess

from ubiquity.plugin import PluginUI, InstallPlugin, Plugin
from ubiquity import misc

import ubunturecovery.recovery_common as magic

NAME = 'ubuntu-partition'
AFTER = 'partman'
BEFORE = 'usersetup'
WEIGHT = 12

class PageNoninteractive (PluginUI):
    pass

class Page(Plugin):
    pass

class Install(InstallPlugin):

    def __init__(self, frontend, db=None, ui=None):
        self.platinfo = magic.PlatInfo()
        InstallPlugin.__init__(self, frontend, db, ui)

    def is_home_mounted(self):
        """Checks to see if /home is already mounted"""
        result = False

        with open('/proc/mounts', 'r') as mounts:
            for line in mounts.readlines():
                if '/home' in line:
                    result = True
                    break
        return result

    def install(self, target, progress, *args, **kwargs):
        if 'UBIQUITY_OEM_USER_CONFIG' in os.environ:
            return

        create_home_partition = misc.create_bool(self.db.get('ubuntu-recovery/create_home_partition'))
        if not create_home_partition:
            return
        
        #dynamically determine where the /home is in case we eliminate the swap partition.
        self.device = subprocess.check_output('findfs LABEL=User_Data', shell=True).decode('utf-8').strip('\n')

        result = self.is_home_mounted()

        if not result:
            # Mount /home so the oem user's home directory is in the right place.
            misc.execute_root('mount', self.device, '/target/home')

            # Add the fstab entry for /home so it will be automounted.
            with misc.raised_privileges():
                f = open('/target/etc/fstab', 'a')
                f.write('\n# Mount /home\n')
                f.write('%s  /home   ext4    defaults    0       2\n' % self.device)
                f.close()
