#include "pkgrm.h"
#include <unistd.h>

int pkgrm::run(int argc, char** argv)
{
   string o_package;
   string o_root;

   for (int i = 1; i < argc; i++) {
      string option(argv[i]);
      if (option == "-r" || option == "--root") {
         check_argument(argv, argc, i);
         o_root = argv[i + 1];
         i++;
      } else if (option == "-v" || option == "--version") {
         print_version();
      } else if (option == "-h" || option == "--help") {
         print_help();
      } else if (option[0] == '-' || !o_package.empty()) {
         print_invalid_option(option);
      } else {
         o_package = option;
      }
   }

   if (o_package.empty())
      print_option_missing();

   //
   // Check UID
   //
   if (getuid()) {
      print_error() << "only root can remove packages" << endl;
      return EXIT_ERROR;
   }

   //
   // Remove package
   //
   db_open(o_root);

   if (!db_find_pkg(o_package)) {
      print_error() << "package " << o_package << " not installed" << endl;
      return EXIT_ERROR;
   }

   db_rm_pkg(o_package);

   db_commit();

   return EXIT_OK;
}

void pkgrm::print_help() const
{
   cout << "Usage: " << name() << " [OPTION]... [PACKAGE]..." << endl
	<< "Remove a package from the system." << endl << endl
        << "  -r, --root <path>   use alternative root directory" << endl
        << "  -h, --help          print this help and exit" << endl
        << "  -v, --version       output version information and exit" << endl << endl
	<< "Report bugs to <johne@rootlinux.org>." << endl;
   exit(EXIT_OK);
}