#!/usr/bin/python3
# Copyright (C) 2025  FreeIPA Contributors see COPYING for license

"""
pkidestroy - PKI instance uninstaller (Dogtag-compatible)

Removes ipacta instance state (service, instance files, compat shims)
without destroying the CA cert/key or NSS database, so the instance
can be re-created with pkispawn.
"""

import sys
import argparse
import types


class PKIDestroy:
    """PKI instance destroyer — Dogtag-compatible wrapper.

    Maps Dogtag pkidestroy arguments to UninstallOrchestrator and
    calls it directly, the same way pkispawn calls
    InstallOrchestrator.
    """

    def __init__(self):
        self.verbose = False

    def destroy_instance(self, subsystem='CA', instance_name='pki-tomcat',
                         force=False, remove_conf=False, remove_logs=False):
        """Destroy a PKI instance or subsystem."""
        print(f"Removing {subsystem} subsystem from {instance_name}...")

        if not force:
            response = input(
                "Are you sure you want to remove this instance? "
                "[y/N]: ")
            if response.lower() not in ['y', 'yes']:
                print("Cancelled")
                return 0

        from ipacta.cli.uninstall import UninstallOrchestrator

        args = types.SimpleNamespace(
            purge=False,
            keep_config=not remove_conf,
            ldap_uri=None,
            unattended=True,
            verbose=self.verbose,
            debug=False,
            instance=instance_name,
            remove_conf=remove_conf,
            remove_logs=remove_logs,
            subsystem=subsystem,
        )

        if subsystem == 'KRA':
            from ipacta.install import NSSDB, ServiceMgmt

            NSSDB.remove_kra_certs(instance_name)
            ServiceMgmt._remove_kra_files(
                instance_name,
                remove_conf=remove_conf,
                remove_logs=remove_logs,
            )
        else:
            uninstaller = UninstallOrchestrator(args)
            rc = uninstaller.run()
            if rc != 0:
                return rc

        print(f"{subsystem} subsystem removed successfully")
        return 0

    def run(self, argv):
        """Main entry point"""
        parser = argparse.ArgumentParser(
            description='PKI instance uninstaller (ipacta)',
            usage='pkidestroy [OPTIONS]'
        )

        parser.add_argument('-s', '--subsystem', default='CA',
                            help='Subsystem to remove (default: CA)')
        parser.add_argument('-i', '--instance', default='pki-tomcat',
                            help='Instance name (default: pki-tomcat)')
        parser.add_argument('-v', '--verbose', action='store_true',
                            help='Verbose mode')
        parser.add_argument('--force', action='store_true',
                            help='Force removal without confirmation')
        parser.add_argument('--remove-conf', action='store_true',
                            help='Remove configuration files')
        parser.add_argument('--remove-logs', action='store_true',
                            help='Remove log files')
        parser.add_argument('--log-file', default=None,
                            help='Log file path (compatibility, ignored)')

        if len(argv) == 1 or '--help' in argv or '-h' in argv:
            parser.print_help()
            return 0

        args = parser.parse_args(argv[1:])
        self.verbose = args.verbose

        return self.destroy_instance(
            args.subsystem, args.instance,
            force=args.force,
            remove_conf=args.remove_conf,
            remove_logs=args.remove_logs,
        )


def main():
    """Main entry point"""
    destroyer = PKIDestroy()
    try:
        sys.exit(destroyer.run(sys.argv))
    except KeyboardInterrupt:
        sys.exit(1)
    except Exception as e:
        print(f"Error: {e}", file=sys.stderr)
        if destroyer.verbose:
            import traceback
            traceback.print_exc()
        sys.exit(1)


if __name__ == '__main__':
    main()
