#!/usr/bin/env python3
import argparse
import configparser
import os
import subprocess
import sys
from datetime import datetime

DEFAULT_EK = "0000000000000000000000000000000000000000"

def log(message, is_error=False):
    """Print message with timestamp"""
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    if is_error:
        print(f"[{timestamp}] {message}", file=sys.stderr)
    else:
        print(f"[{timestamp}] {message}")


def load_credentials(path):
    if not os.path.exists(path):
        log(f"Error: credentials file not found: {path}", is_error=True)
        sys.exit(1)

    config = configparser.ConfigParser()
    config.read(path)

    try:
        username = config.get("credentials", "username", fallback="root")
        password = config.get("credentials", "password")
        encryption_key = config.get("credentials", "encryption_key", fallback=DEFAULT_EK)
    except (configparser.NoSectionError, configparser.NoOptionError) as e:
        log(f"Error reading credentials file: {e}", is_error=True)
        sys.exit(1)

    return username, password, encryption_key


def main():
    p = argparse.ArgumentParser(description="Send IPMI power off")
    p.add_argument("-H", "--host", required=True, help="IPMI host address")
    p.add_argument(
        "-c",
        "--credentials",
        default="credentials",
        help="Path to credentials file (default: credentials)",
    )
    args = p.parse_args()

    ipmi_user, ipmi_pw, ipmi_ek = load_credentials(args.credentials)

    cmd = [
        "ipmitool",
        "-I", "lanplus",
        "-H", args.host,
        "-U", ipmi_user,
        "-P", ipmi_pw,
        "-y", ipmi_ek,
        "power", "off",
    ]

    proc = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
    if proc.returncode != 0:
        log("ipmitool failed: " + proc.stderr.strip(), is_error=True)
        sys.exit(proc.returncode)

    log(proc.stdout.strip())

if __name__ == "__main__":
    main()
