#!/usr/bin/python

################################################################
#
# Copyright (c) 2017 SUSE Linux Products GmbH
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 or 3 as
# published by the Free Software Foundation.
#
# 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 program (see the file COPYING); if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
#
################################################################

import websocket
import sys

if len(sys.argv) != 2:
    sys.exit("usage: openstack-console <url>")
ws = websocket.create_connection(sys.argv[1],
                                 header={'Sec-WebSocket-Protocol: binary'})
buf = ''
while True:
    data = ws.recv()
    sys.stdout.write(data)
    if not ws.connected:
        sys.stdout.write("[connection closed]\n")
        break
    buf += data
    buf = buf[-256:]
    if re.searcg("[\r\n]\[\s*[0-9\.]*]\s+reboot: Power down", buf):
        break
ws.close()
