#!/usr/bin/env python3
# Copyright 2017 Canonical Ltd.  This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).

"""Atomically delete a file.

The filename is checked against an internal white list. As such it's intended
to be used behind `sudo`.
"""

import argparse
import os
import pipes

from provisioningserver.utils.fs import atomic_delete


whitelist = {
    "/var/lib/maas/dhcpd.conf",
    "/var/lib/maas/dhcpd6.conf",
}


# For DEVELOPMENT ONLY update the paths in the white list to all be prefixed
# with MAAS_ROOT, if defined. Check real and effective UIDs to be super extra
# paranoid (only the latter actually matters).
if os.getuid() != 0 and os.geteuid() != 0:
    root = os.environ.get("MAAS_ROOT")
    if root is not None:
        whitelist = {
            os.path.abspath(root + os.sep + path)
            for path in whitelist
        }


arg_parser = argparse.ArgumentParser(description=__doc__)
arg_parser.add_argument("filename", help="The file to delete.")


def main(args):

    # Validate the filename here because using a `choices` argument in the
    # parser results in ugly help and error text.
    if args.filename not in whitelist:
        arg_parser.error(
            "Given filename %s is not in the white list. "
            "Choose from: %s." % (
                pipes.quote(args.filename), ", ".join(
                    map(pipes.quote, sorted(whitelist)))))

    # Okay, good to go.
    else:
        try:
            atomic_delete(args.filename)
        except FileNotFoundError:
            pass  # Ignore; it's already gone.


if __name__ == "__main__":
    main(arg_parser.parse_args())
