#!/usr/bin/python3
# SPDX-License-Identifier: BSD-3-Clause
#
# Copyright 2022 Raritan Inc. All rights reserved.

import argparse, difflib, json, sys, os, time
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/pdu-python-api")
from raritan.rpc import Agent
from raritan.rpc.smartlock import DoorAccessControl

# default values
ip = "10.0.42.2"
user = "admin"
pw = "raritan"

parser = argparse.ArgumentParser(description='Remove door access rules from device.')
parser.add_argument('--rule', dest='ruleId', action='store',
                    help='Rule id to delete (or \'all\' or \'expired\')', required=True)
parser.add_argument('--ip', dest='ip', action='store', default=ip, help='ip address')
parser.add_argument('--user', dest='user', action='store', default=user, help='user name')
parser.add_argument('--passwd', dest='pw', action='store', default=pw, help='password')
args = parser.parse_args()

agent = Agent("https", args.ip, args.user, args.pw, disable_certificate_verification = True)
doorAccess = DoorAccessControl("/dooraccesscontrol", agent)
rules = doorAccess.getDoorAccessRules()

deleteAllRules = args.ruleId == "all"
deleteExpiredRules = args.ruleId == "expired"
if deleteAllRules or deleteExpiredRules:
    if len(rules) > 0:
        for ruleId in rules:
            rule = rules[ruleId]
            ruleName = rule.name
            if deleteAllRules:
                print(f"remove rule {ruleId} ({ruleName})")
                doorAccess.deleteDoorAccessRule(ruleId)
            else:
                if not rule.absoluteTime.enabled:
                    print(f"- Rule {ruleId} ({ruleName}) never expires.")
                elif rule.absoluteTime.validTill.encode() > int(time.time()):
                    print(f"- Rule {ruleId} ({ruleName}) is still valid.")
                else:
                    print(f"- Rule {ruleId} ({ruleName}) has expired and will be deleted.")
                    doorAccess.deleteDoorAccessRule(ruleId)
    else:
        print("No door access rules")
else:
    ruleId = int(args.ruleId)
    if ruleId in rules:
        print(f"remove rule {ruleId} ({rules[ruleId].name})")
        doorAccess.deleteDoorAccessRule(ruleId)
    else:
        print(f"No rule with id {ruleId}")
