aboutsummaryrefslogtreecommitdiff
path: root/src/usr/bin/logout-manager-cli
blob: 974fd4bfe0b90c4226ade9b305f8fdf2a85496af (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#!/usr/bin/env python3
# File: logout-manager-cli
# License: CC-BY-SA 4.0
# Author: bgstack15
# Startdate: 2020-03-10 18:40
# Title: cli logout manager
# Purpose: Feature completeness in this package
# History:
#    2020-04-03 fix #5 -n does nothing
# Usage:
#    logout-manager-cli
# Reference:
#    https://stackoverflow.com/questions/39092149/argparse-how-to-make-mutually-exclusive-arguments-optional/39092229#39092229
#    https://stackoverflow.com/questions/3061/calling-a-function-of-a-module-by-using-its-name-a-string/12025554#12025554
# Improve:
# Dependencies:
#    dep-devuan: python3-dotenv, python3
# Documentation:

import os, sys, argparse
from distro import linux_distribution
from dotenv import load_dotenv

# all this to load the libpath
try:
   defaultdir="/etc/sysconfig"
   thisplatform = linux_distribution()[0].lower()
   if 'debian' in thisplatform or 'devuan' in thisplatform:
      defaultdir="/etc/default"
   # load_dotenv keeps existing environment variables as higher precedent
   load_dotenv(os.path.join(defaultdir,"logout-manager"))
except:
   pass
if 'LOGOUT_MANAGER_LIBPATH' in os.environ:
   for i in os.environ['LOGOUT_MANAGER_LIBPATH'].split(":"):
      sys.path.append(i)
sys.path.append("/usr/share/logout-manager")
import lmlib

def eprint(*args, **kwargs):
   print(*args, file=sys.stderr, **kwargs)

logout_manager_cli_version="2020-04-03"

parser = argparse.ArgumentParser(description="run logout-manager commands using cli")
parser.add_argument('action', help='which action to take',nargs='?', choices=('lock','logout','hibernate','shutdown','reboot'))
parser.add_argument("-d","--debug", nargs='?', default=0, type=int, choices=range(0,11), help="Set debug level.")
parser.add_argument("-n","--dryrun", action='store_true', help="only report. Useful for checking if hibernate is allowed.")
parser.add_argument("-V","--version", action="version", version="%(prog)s " + logout_manager_cli_version)

args = parser.parse_args()

# handle -n
if args.dryrun:
   os.environ["DRYRUN"] = "from-parameters"

# load configs
# in cli, must happen after arparse to benefit from debug value
config = lmlib.Initialize_config(os.environ['LOGOUT_MANAGER_CONF'])
actions = lmlib.Actions

# MAIN LOOP
allowed_actions=['lock','logout','shutdown','reboot']
if config.can_hibernate:
   allowed_actions.append('hibernate')

if args.action in allowed_actions:
   func = getattr(globals()['actions'],args.action)
   func(config)
   sys.exit(0)
elif args.action:
   eprint("Unable to take action: %s" % str(args.action))
   sys.exit(1)

# if we get here, no action was used
parser.print_help()
sys.exit(2)
bgstack15