#!/usr/bin/env python3
import argparse
import subprocess
import getpass
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}")

def run(cmd):
    try:
        subprocess.run(cmd, check=True)
    except subprocess.CalledProcessError as e:
        print(f"Command failed: {' '.join(cmd)}", file=sys.stderr)
        sys.exit(e.returncode)

def main():
    p = argparse.ArgumentParser(description="Login to iLO, show serverinfo and power on")
    p.add_argument("-H", "--host", required=True, help="iLO host/IP")
    p.add_argument("-a", "--action", default="On", choices=["On","Off","GracefulRestart","ForceOff","Reset"],
                   help="power/reboot action to run (default: On)")
    p.add_argument("--no-serverinfo", action="store_true", help="skip running serverinfo")
    args = p.parse_args()

    ts_print(f"Sending {args.action} to {args.host}")
    run(['ilorest', 'login', args.host, '-u', '<username>', '-p', '<password>'])
    if not args.no_serverinfo:
        run(['ilorest', 'serverinfo'])
    run(['ilorest', 'reboot', args.action])

if __name__ == "__main__":
    main()