#!/bin/sh -efu
#
# Copyright (C) 2023 Evgeny Sinelnikov <sin@altlinux.org>
#
# This file 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, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
#

. shell-args
. shell-error
. shell-getopt

verbose=

show_help() {
  cat <<-EOF
		Usage: $PROG [options] <command>

		Commands:
		  list                    show packages list with name, version, release, arch and group
		  install                 install package from file
		  remove                  remove package by package name
		  info                    show package information by package name
		  files                   show files in package by package  name

		Options:
		  -V, --version           print program version and exit;
		  -h, --help              show this text and exit.

		Report bugs to http://bugzilla.altlinux.org/

	EOF
  exit
}

print_version() {
  echo "@VERSION@"
  exit
}

TEMP=$(getopt -n $PROG -o $getopt_common_opts -l $getopt_common_longopts,package-path:,package-name: -- "$@") ||
  show_usage
eval set -- "$TEMP"

while :; do
  case "$1" in
  --package-path)
	shift
	pkgpath="$1"
	test -f "$pkgpath"
	;;
  --package-name)
	shift
	pkgname="$1"
	echo "$pkgname" | grep -q '^[a-zA-Z0-9][a-zA-Z0-9_+-]*'
	;;
  --)
	shift
	break
	;;
  *)
	parse_common_option "$1"
	;;
  esac
  shift
done

[ "$#" -gt 0 ] ||
  show_usage

case "$1" in
list)
  rpm -qa --qf "%{NAME} %{VERSION} %{RELEASE} %{ARCH} %{GROUP}\n"
  ;;
install)
  rpm -U "$pkgpath"
  ;;
remove)
  rpm -e "$pkgname"
  ;;
info)
  rpm -qi "$pkgname"
  ;;
files)
  rpm -ql "$pkgname"
  ;;
*)
  fatal "Unknown command: $1"
  ;;
esac
