import { ipset } from "netfilter";
import util from "util";

const ipset_create = util.promisify(ipset.create);
const ipset_add = util.promisify(ipset.add);
const ipset_del = util.promisify(ipset.del);
const ipset_test = util.promisify(ipset.test);

export class IPSetHelper {
	static async create(setname: string): Promise<string> {
		try {
			await ipset_create({
				setname,
				type: "hash:net",
				create_options: {
					maxelem: 1000000
				}
			});
			return null;
		} catch(e) {
			return e.toString();
		}
	}
	static async add(setname: string, address: string): Promise<string> {
		try {
			await ipset_add({
				setname,
				entry: address
			});
			return null;
		} catch(e) {
			return e.toString();
		}
	}
	static async del(setname: string, address: string): Promise<string> {
		try {
			await ipset_del({
				setname,
				entry: address
			});
			return null;
		} catch(e) {
			return e.toString();
		}
	}
	static async test(setname: string, address: string): Promise<boolean> {
		try {
			await ipset_test({
				setname,
				entry: address
			});
			return true;
		} catch(e) {
			return false;
		}
	}
}
