#!/usr/bin/python3

# This file is part of Cockpit.
#
# Copyright (C) 2015 Red Hat, Inc.
#
# Cockpit is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
# Cockpit 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Cockpit; If not, see <http://www.gnu.org/licenses/>.

import glob
import os.path
import shutil
import tempfile
import tarfile

import parent
from testlib import *


class TestSOS(MachineCase):

    def testBasic(self, urlroot=""):
        b = self.browser
        m = self.machine

        m.write("/etc/sos.conf",
                """
[general]
only-plugins=release,date,host
threads=2
""")

        if urlroot != "":
            m.execute('mkdir -p /etc/cockpit/ && echo "[WebService]\nUrlRoot=%s" > /etc/cockpit/cockpit.conf' % urlroot)

        self.login_and_go("/sosreport", urlroot=urlroot)

        b.click('[data-target="#sos"]')
        b.wait_visible("#sos")

        with b.wait_timeout(360):
            b.wait(lambda: b.eval_js('ph_find(".progress-bar").offsetWidth') > 0)
            b.wait_visible("#sos-download")

        download_dir = tempfile.mkdtemp()
        self.addCleanup(shutil.rmtree, download_dir)
        b.cdp.invoke("Page.setDownloadBehavior", behavior="allow", downloadPath=download_dir)

        b.click("#sos-download button")
        # while the download is ongoing, it will have an *.xz.tmpsuffix name, gets renamed to *.xz when done
        wait(lambda: len(glob.glob(os.path.join(download_dir, "sosreport-*.xz"))) > 0)
        report = glob.glob(os.path.join(download_dir, "sosreport-*.xz"))[0]
        # Check that /etc/release was saved. It the files does not exist, getmember raises KeyError
        with tarfile.open(report) as tar:
            tar.getmember(os.path.join(tar.getnames()[0], "etc/os-release"))

        self.allow_journal_messages('.*comm="sosreport".*')

    def testWithUrlRoot(self):
        self.testBasic(urlroot="/webcon")

    @skipImage("Not supported", "fedora-atomic")
    def testAppStream(self):
        b = self.browser
        m = self.machine

        self.allow_journal_messages("invalid or unusable locale.*")

        self.login_and_go("/apps")
        b.wait_not_present(".app-list-empty .spinner")
        image_os = m.image.split('-')[0]
        if image_os in ['fedora', 'debian', 'ubuntu']:
            b.wait_present(".app-list tr:contains('Diagnostic Reports')")
            b.wait_present(".app-list tr:contains('Diagnostic Reports') button:contains('Remove')")
        else:
            b.wait_not_present(".app-list tr:contains('Diagnostic Reports')")


if __name__ == '__main__':
    test_main()
