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

def ts_print(msg):
    """ts_print message prefixed with a timestamp (YYYY-MM-DD HH:MM:SS)."""
    now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    print(f"{now} {msg}")

DEFAULT_EK = "0000000000000000000000000000000000000000"


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

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

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

    return username, password, encryption_key

def main():
    p = argparse.ArgumentParser(description="Send IPMI power on")
    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", "on",
    ]
    print(f"Sending power on to {args.host}")
    proc = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
    if proc.returncode != 0:
        print("ipmitool failed:", proc.stderr.strip(), file=sys.stderr)
        sys.exit(proc.returncode)
    print(proc.stdout.strip())

if __name__ == "__main__":
    main()
