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

# This file is part of Cockpit.
#
# Copyright (C) 2013 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 parent
from testlib import *

class TestTerminal(MachineCase):
    provision = { "machine1": { "dns": "127.0.0.1" } }

    def testBasic(self):
        b = self.browser
        m = self.machine
        b.default_user = "admin"

        # Make sure we get what we expect
        m.write("/tmp/bashrc-extra", """
PS1="\\u@\\h \\W]\$ "
PROMPT_COMMAND='printf "\\033]0;%s@%s:%s\\007" "${USER}" "${HOSTNAME%%.*}" "${PWD/#$HOME/\~}"'
""")
        m.execute("cat /tmp/bashrc-extra >>/home/admin/.bashrc")

        self.login_and_go("/system/terminal")

        def line_sel(i):
            return '.terminal div:nth-child(%d)' % i

        def wait_line(i,t):
            b.wait_in_text(line_sel(i), t)

        b.wait_present('.terminal')
        b.focus('.terminal')

        # wait until first line is not empty
        n = 1
        b.wait_js_func("(function (sel) { return ph_text(sel).trim() != ''})", line_sel(n))

        # clear any messages (for example, instructions about sudo) and wait for prompt
        b.key_press("clear")
        b.wait_js_cond("ph_text('.terminal').indexOf('clear') >= 0")
        # now wait for clear to take effect
        b.key_press("\r")
        b.wait_js_cond("ph_text('.terminal').indexOf('clear') < 0")
        # now we should get a clean prompt
        wait_line(n, "$")

        # cut trailing non-breaking spaces
        prompt = b.text(line_sel(n)).rstrip()

        # Make sure we are started in home directory
        # Account for non-standard prompting
        if "]" not in prompt:
            self.assertIn(":~$", prompt)
        else:
            self.assertIn("~]$", prompt)

        # Run some commands
        b.key_press("whoami\r")
        wait_line(n + 1, "admin")

        wait_line(n + 2, prompt)

        b.key_press('echo -e "1\\u0041"\r')
        wait_line(n + 3, '1A')

        # The '@' sign is in the default prompt
        b.wait_in_text(".terminal-title", '@')

        # now reset terminal
        b.click('.btn:contains("Reset")')

        # assert that the output from earlier is gone
        self.assertNotIn('admin', b.text(line_sel(n + 1)))

if __name__ == '__main__':
    test_main()
