#!/usr/bin/env python
#
#	pypaxctl: this file is part of the elfix package
#	Copyright (C) 2011, 2012  Anthony G. Basile
#
#	This program is free software: you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation, either version 3 of the License, or
#	(at your option) any later version.
#
#	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.  If not, see <http://www.gnu.org/licenses/>.
#


import sys
import getopt
import pax

xattr_available = True
try:
	from pax import deletextpax
except ImportError:
	xattr_available = False

def run_usage():
	print('Package Name : elfix')
	print('Bug Reports  : http://bugs.gentoo.org/')
	print('Program Name : pypaxctl')
	if xattr_available:
		print('Description  : Get/set/delete PT_PAX or XATTR_PAX flags on an ELF object')
		print('')
		print('Usage        : pypaxctl -g ELF                get XATTR_PAX flags first, else get PT_PAX flags')
		print('             : pypaxctl -s [-PpEeMmRrSs] ELF  set PT_PAX and XATTR_PAX flags whenever possible')
		print('             : pypaxctl -d ELF                delete the XATTR_PAX field')
	else:
		print('Description  : Get/set PT_PAX flags on an ELF object')
		print('')
		print('Usage        : pypaxctl -g ELF                get PT_PAX flags')
		print('             : pypaxctl -s [-PpEeMmRrSs] ELF  set PT_PAX flags whenever possible')
		print('')
		print('Note         : Python module pax.so was compiled without XATTR_PAX support')
	print('')


def main():
	try:
		if xattr_available:
			opts, args = getopt.getopt(sys.argv[1:], 'gs:d')
		else:
			opts, args = getopt.getopt(sys.argv[1:], 'gs:')
	except getopt.GetoptError as err:
		print(err)
		sys.exit(1)

	if( len(opts) != 1 or len(args) < 1 ):
		run_usage()
		sys.exit(1)

	for o, a in opts:
		if o == '-g':
			for elf in args:
				( str_flags, bin_flags ) = pax.getflags(elf)
				print('%s' % str_flags)
		elif o == '-s':
			for elf in args:
				pax.setstrflags(elf, a)

		# Don't worry if xattr_available = False
		# because we can't get here if it is.
		else:
			for elf in args:
				try:
					pax.deletextpax(elf)
				except pax.PaxError:
					print('pax_deletextpax: XATTR_PAX not supported')
					sys.exit(1)

if __name__ == '__main__':
	main()
