#!/usr/bin/env python3
import sys
import os

from clint import arguments
from clint.textui import puts, indent, colored

from dpkgunlockercli import DpkgUnlockerCli


def usage():
	puts("Usage")
	with indent(4):
		puts("dpkgunlocker-cli [FLAGS...] ACTION")
		puts("Actions")
		with indent(4):	
			puts("showservices: Show information about the status of services involved in installation of packages")
			puts("unlock: Run command to try to recover the blocked services")
			puts("showprotection: Show the current state of system metapackage protection")
			puts("disableprotetion: Run command to disable system metapackage protection")
			puts("enableprotection: Run command to enable system metapackage protection")		
			puts("restore: Run command to try to restore services involved in package installation")
		
		puts("Flags")
		with indent(4):
			puts("-h --help : Show help")
			puts("-u --unattended: Run the command without prompting for user confirmation")
			puts("-k --kill: Run the unlock command killing the associated running process. It can cause problems if used incorrectly ")

	sys.exit(1)

#def usage	

def isDpkgUnlockerRunning():

	if os.path.exists('/var/run/dpkgUnlocker.lock'):
		print("  [Dpkg-Unlocker-Cli]: Dpkg-Unlocker is now running. Wait a moment and try again")
		sys.exit(1)

#def isDpkgUnlockedRunning

		
if __name__ == '__main__':

	if os.geteuid() != 0:
		print("  [DpkgUnlocker-Cli]: You need be root!")
		sys.exit(1)

	isDpkgUnlockerRunning()
		
	args = arguments.Args().copy
	mode=False
	kill=False

	if args.contains(["-h","--help"]) or len(args.all) == 0 :
		usage()		
	if args.contains(["-u","--unattended"]):
		mode=True
		index = args.first(["-u","--unattended"])
		args.pop(index)
	if args.contains(["-k","--kill"]):
		kill=True
		index = args.first(["-k","--kill"])
		args.pop(index)


	action = args.pop(0)

	dpkgunlockercli = DpkgUnlockerCli(args.get(0))
	if action == "showservices":
		sys.exit(dpkgunlockercli.showServices())
	elif action=="unlock":
		sys.exit(dpkgunlockercli.unlock(mode,kill))	
	elif action=="showprotection":
		sys.exit(dpkgunlockercli.showProtection())
	elif action=="disableprotection":
		sys.exit(dpkgunlockercli.disableProtection(mode))
	elif action=="enableprotection":
		sys.exit(dpkgunlockercli.enableProtection(mode))
	elif action=="restore":
		sys.exit(dpkgunlockercli.restore(mode))
	else:
		dpkgunlockercli.dpkgUnlockerCore.cleanLockToken()
		usage()