#!/usr/bin/python3
import argparse
import configparser
import os
import sys
import urllib3
import redfish

# Suppress SSL warnings for self-signed iLO certificates
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

parser = argparse.ArgumentParser(description="Get the power status of an HPE server via iLO Redfish")
parser.add_argument("hostname", help="iLO hostname or IP address")
parser.add_argument("-c", "--credentials", default="/etc/ilo_credentials",
                    help="Path to credentials file (default: /etc/ilo_credentials)")
args = parser.parse_args()

# Read credentials from file (chmod 600 recommended: sudo chmod 600 /etc/ilo_credentials)
# File format:
#   [ilo]
#   username = root
#   password = yourpassword
cred_path = args.credentials
if not os.path.exists(cred_path):
    print(f"Error: credentials file not found: {cred_path}", file=sys.stderr)
    sys.exit(1)

config = configparser.ConfigParser()
config.read(cred_path)
try:
    LOGIN_ACCOUNT = config.get("ilo_credentials", "username", fallback="root")
    LOGIN_PASSWORD = config.get("ilo_credentials", "password")
except (configparser.NoSectionError, configparser.NoOptionError) as e:
    print(f"Error reading credentials file: {e}", file=sys.stderr)
    sys.exit(1)

BASE_URL = f"https://{args.hostname}"

REDFISHOBJ = redfish.RedfishClient(
    base_url=BASE_URL,
    username=LOGIN_ACCOUNT,
    password=LOGIN_PASSWORD,
)
REDFISHOBJ.login(auth="session")

sys_response = REDFISHOBJ.get("/redfish/v1/Systems/1/")
power_state = sys_response.dict.get("PowerState", "Unknown")

print(f"Power State: {power_state}")

REDFISHOBJ.logout()
