#!/usr/bin/python
#
# Obtain CT status and max memory size.
# Shaman master executes this script to prepare data for pdrs
# during resource relocation.
#
# RESOURCE_PATH environment variable points to CT private area
# output : "<CT:subtype>/n<CT max memory size in KB>"
#
# Copyright (c) 2013-2017, Parallels International GmbH
# Copyright (c) 2017-2019 Virtuozzo International GmbH. All rights reserved.
#
# Our contact details: Virtuozzo International GmbH, Vordergasse 59, 8200
# Schaffhausen, Switzerland.
#

from __future__ import print_function
import sys
import os
import shlex
sys.path.append('/usr/share/shaman')
import shaman_functions as shaman


def error(msg):
    print(msg, file=sys.stderr)


def get_env(name):
    '''Get the value of a given environment variable'''
    val = os.environ.get(name)
    if not val:
        error('%r environment variable undefined' % name)
        sys.exit(1)
    return val

try:
    path = get_env('RESOURCE_PATH')
    if not os.path.exists(os.path.join(path, '.running')):
        error('CT %r is not running -- skip it' % path)
        sys.exit(0)
    conf = os.path.join(path, 've.conf')
    if not os.path.exists(conf):
        error("CT's config %r does not exist -- skip it" % conf)
        sys.exit(2)

    pages = long(0)
    with open(conf, 'r') as f:
        for line in shlex.split(f.read(), True):
            v = line.split('=')
            if v[0] == 'PHYSPAGES':
                # PHYSPAGES=soft:hard -- we need hard limit
                pages = long(v[1].split(':')[1])
                break
    if pages == 0:
        error('can not find PHYSPAGES value in %r -- skip it' % conf)
        sys.exit(3)

    flavor = shaman.CtConfig(path).get_flavor()
    if not flavor:
        error('can not get the flavor of CT %r -- skip it' % path)
        sys.exit(4)
    print('{0}\n{1}'.format(flavor, pages * 4))
except SystemExit:
    raise
except:
    error('Unexpected error: %s' % sys.exc_info()[0])
    raise
