1#!/usr/bin/env python
2#
3#   (C) 2001 by Argonne National Laboratory.
4#       See COPYRIGHT in top-level directory.
5#
6
7"""
8usage: mpdexit mpdid
9    mpdid may be obtained via mpdtrace -l (or may be "localmpd")
10Causes a single mpd to exit (and thus exit the ring).
11Note that this may cause other mpds to become 'isolated' if they
12entered the ring through the exiting one.
13"""
14from time import ctime
15__author__ = "Ralph Butler and Rusty Lusk"
16__date__ = ctime()
17__version__ = "$Revision: 1.15 $"
18__credits__ = ""
19
20
21import sys, os, signal
22
23from  mpdlib  import  mpd_set_my_id, mpd_uncaught_except_tb, mpd_print, \
24                      mpd_handle_signal, mpd_get_my_username, \
25                      MPDConClientSock, MPDParmDB
26
27def mpdexit():
28    import sys    # to get access to excepthook in next line
29    sys.excepthook = mpd_uncaught_except_tb
30    if (len(sys.argv) > 1  and  (sys.argv[1] == '-h'  or  sys.argv[1] == '--help')) or \
31       (len(sys.argv) < 2):
32	print __doc__
33        sys.exit(-1)
34    signal.signal(signal.SIGINT, sig_handler)
35    mpd_set_my_id(myid='mpdexit')
36
37    parmdb = MPDParmDB(orderedSources=['cmdline','xml','env','rcfile','thispgm'])
38    parmsToOverride = {
39                        'MPD_USE_ROOT_MPD'            :  0,
40                        'MPD_SECRETWORD'              :  '',
41                      }
42    for (k,v) in parmsToOverride.items():
43        parmdb[('thispgm',k)] = v
44    parmdb.get_parms_from_env(parmsToOverride)
45    parmdb.get_parms_from_rcfile(parmsToOverride)
46    if (hasattr(os,'getuid')  and  os.getuid() == 0)  or  parmdb['MPD_USE_ROOT_MPD']:
47        fullDirName = os.path.abspath(os.path.split(sys.argv[0])[0])  # normalize
48        mpdroot = os.path.join(fullDirName,'mpdroot')
49        conSock = MPDConClientSock(mpdroot=mpdroot,secretword=parmdb['MPD_SECRETWORD'])
50    else:
51        conSock = MPDConClientSock(secretword=parmdb['MPD_SECRETWORD'])
52
53    msgToSend = { 'cmd' : 'mpdexit', 'mpdid' : sys.argv[1] }
54    conSock.send_dict_msg(msgToSend)
55    msg = conSock.recv_dict_msg(timeout=5.0)
56    if not msg:
57        mpd_print(1,'no msg recvd from mpd before timeout')
58        sys.exit(-1)
59    elif msg['cmd'] == 'already_have_a_console':
60        mpd_print(1,'mpd already has a console (e.g. for long ringtest); try later')
61        sys.exit(-1)
62    if not msg.has_key('cmd'):
63        mpd_print(1,'mpdexit: INVALID msg=:%s:' % (msg))
64        sys.exit(-1)
65    if msg['cmd'] != 'mpdexit_ack':
66        mpd_print(1,'mpdexit failed; may have wrong mpdid')
67        sys.exit(-1)
68
69def sig_handler(signum,frame):
70    mpd_handle_signal(signum,frame)  # not nec since I exit next
71    sys.exit(-1)
72
73def usage():
74    print __doc__
75    sys.exit(-1)
76
77if __name__ == '__main__':
78    mpdexit()
79