Mini Shell

Direktori : /proc/self/root/proc/thread-self/root/opt/tier1adv/bin/
Upload File :
Current File : //proc/self/root/proc/thread-self/root/opt/tier1adv/bin/rmlocaldomain

#!/opt/imh-python/bin/python3
"""Moves a domain between /etc/remotedomains and /etc/localdomains"""

from argparse import ArgumentParser
from pathlib import Path
import sys

# addlocaldomain is symlinked to rmlocaldomain
ADDING = 'addlocal' in sys.argv[0]
ADD_PATH = Path('/etc/localdomains') if ADDING else Path('/etc/remotedomains')
RM_PATH = Path('/etc/remotedomains') if ADDING else Path('/etc/localdomains')


def parse_args() -> list[str]:
    """Obtain list of domains from CLI args"""
    parser = ArgumentParser(description=f"move a domain to {ADD_PATH}")
    parser.add_argument(
        'domain',
        metavar='DOMAIN',
        nargs='+',
        help=f'list of domains to move to {ADD_PATH}',
    )
    args = parser.parse_args()
    return args.domain


def remove_domains(domains: list[str]) -> None:
    """Remove list of domains"""
    file_lines = RM_PATH.read_text(encoding='utf-8').splitlines()
    save = False
    for domain in domains:
        if domain in file_lines:
            print(f"Removing {domain} from {RM_PATH}.")
            save = True
        else:
            print(f"{domain} was not in {RM_PATH}.")
    if not save:
        return
    data = '\n'.join([x for x in file_lines if x not in domains])
    save_data(RM_PATH, f"{data}\n")


def add_domains(domains: list[str]) -> None:
    """Add list of domains"""
    file_lines = ADD_PATH.read_text(encoding='utf-8').splitlines()
    save = False
    for domain in domains:
        if domain in file_lines:
            print(f"{domain} was already in {ADD_PATH}.")
        else:
            print(f"Adding {domain} to {ADD_PATH}.")
            file_lines.append(domain)
            save = True
    if not save:
        return
    data = '\n'.join(file_lines)
    save_data(ADD_PATH, f"{data}\n")


def save_data(path: Path, data: str) -> None:
    """Save to a {path}.tmp then mv to {path} to avoid race conditions"""
    tmp_path = path.parent.joinpath(f"{path.name}.tmp")
    tmp_path.write_text(data, encoding='utf-8')
    tmp_path.rename(path)


def main():
    """Collect args, remove from local domains, add to remote,
    or vice versa if called through addlocaldomain"""
    doms = parse_args()
    remove_domains(doms)
    add_domains(doms)


if __name__ == '__main__':
    main()

Zerion Mini Shell 1.0