# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
#!/usr/bin/env python3
# -*- encoding=utf8 -*-
#
import unittest
import shutil
import tempfile
import os
from ubunturecovery import grub

class GrubCfgTestCase(unittest.TestCase):

    def setUp(self):
        self.target = tempfile.mkdtemp()
        self.tpldir = tempfile.mkdtemp()
        self.tplname = 'grub.cfg.tpl'
        self.installer = grub.GrubInstaller(self.target, self.tpldir)
        self.tplpath = self.installer.tplpath(self.tplname)
        self._tpl = ['menuentry "Automated Installation of #OS# (Default)" {',
                        'set recordfail=1',
                        'if [ -n "${have_grubenv}" ]; then save_env recordfail; fi',
                        'linux /casper/vmlinuz $options $loop_options',
                        'initrd /casper/initrd.lz']
        # create /boot/grub/ in tmp target directory
        os.system('mkdir -p ' + self.installer.cfgpath(''))

    def tearDown(self):
        shutil.rmtree(self.target)
        shutil.rmtree(self.tpldir)

    def _write(self, lines):
        with open(self.tplpath, 'w') as fileobj:
            fileobj.write('\n'.join(lines + ['']))

    def _write_tpl(self):
        self._write(self._tpl)

    def test_set(self):
        self._write_tpl()
        self.cfg = grub.GrubCfg.create(self.tplpath, self.tplpath)
        self.cfg.set(os='Ubuntu')

    def test_save(self):
        self.test_set()
        self.cfg.save()

        with open(self.tplpath) as nfd:
            self.assertEquals(repr(self.cfg), nfd.read())

    def test_addheadera(self):
        self.test_set()
        header = ['partool set (hd0,1) boot+']
        self.cfg.addheaders(header)
        assertstr = '\n'.join(header + self._tpl)
        self.assertEquals(repr(self.cfg),
                          assertstr.replace('#OS#', 'Ubuntu')+'\n')

    def test_cfg(self):
        self._write_tpl()
        cfg = self.installer.create_cfg('grub.cfg', self.tplpath)
        self.assertEquals(os.path.join(self.target, 'boot', 'grub', 'grub.cfg'),
                          cfg.path)

    def test_instcfg(self):
        testline = 'uuid : #UUID#'
        data = {'uuid':'UUAIS1',
                'rp_part':'msdos1'
        }
        self._instcfg(testline, data)

    def test_instcfg_emptydata_tpl(self):
        testline = 'uuid : #UUID#'
        self.assertRaises(TypeError, self._instcfg, testline, {})

    def test_instcfg_emptydata_ntpl(self):
        self._instcfg('', {})

    def _instcfg(self, testline, data):
        self._tpl.append(testline)
        self._write_tpl()
        files = {self.tplname:'grub.cfg'}
        self.installer.install_rp_grubcfg(files, data)
        cfgpath = self.installer.cfgpath(files[self.tplname])
        self.assertTrue(os.path.exists(cfgpath))

def suite():
    suite = unittest.TestSuite()
    suite.addTest(unittest.makeSuite(GrubCfgTestCase, 'test'))
    return suite

if __name__ == '__main__':
    unittest.main(defaultTest='suite')
