#!/usr/bin/env python3
#===============================================================================
# DIRECTORY:
#   /usr/local/bin
#
# FILE:
#   print_plist_entry.py
#
# USAGE:
#   ./print_plist_entry.py <plist> <key>
#     OR
#   python3 print_plist_entry.py <plist> <key>
#
# OPTIONS:
#   none
#
# DESCRIPTION:
#   Prints key-value pair of key in plist
#
# REQUIREMENTS:
#   python3 and python-plistlib
#
# BUGS:
#   ---
#
# NOTES:
#   Tested on:
#   - Arch Linux
#
# AUTHOR:
#   Patrick Neumann, patrick@neumannsland.de
#
# COMPANY:
#   (privately)
#
# VERSION:
#   0.9 (beta)
#
# LINK TO THE MOST CURRENT VERSIONS:
#   https://...
#
# CREATED:
#   17.11.2020
#
# COPYRIGHT (C):
#   2015-2020 - Patrick Neumann
#
# LICENSE:
#   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.
#
# WARRANTY:
#   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/>.
#
# TODO:
#   ---
#
# HISTORY:
#   0.9 - Patrick Neumann - Initial (public) release
#
#===============================================================================

import os.path
import plistlib
import sys

# short help for new users
def usage():
  print( "\nUsage: python print_plist_entry.py <plist> <key>\n" )
  print( "  (use the <key> \"ALL\" to list all entries.)\n" )

# check for first parameter
try:
  plist = sys.argv[1]
except IndexError:
  print( "\nError: No <plist> (file) given!" )
  usage()
  sys.exit( 1 )

# check if first parameter is a file
if not os.path.isfile( plist ):
  print( "\nError: plist (file) does not exist!\n" )
  sys.exit( 1 )

# check for second parameter
try:
  key = sys.argv[2]
except IndexError:
  print( "\nError: No <key> (string) given!" )
  usage()
  sys.exit( 1 )

# plist has to be a XML file
try:
  with open( plist, 'rb' ) as fp:
    content = plistlib.load( fp )
except:
  print( "\nError: plist is not a XML file!\n" )
  sys.exit( 1 )

try:
  print( key + ":", content[ key ] )
except:
  print( "\nError: key not found!\n" )
  sys.exit( 1 )

sys.exit( 0 )