#!/usr/bin/python

# Copyright (c) 2013 Isilon Systems LLC. All rights reserved.

import sys
import syslog
import os

import isi.hw.bay as bay
import isi.hw.sed as sed
import isi.hw.hal as hal

def main():
    pids = []
    result = 0
  
    if not hal.supportsSelfEncryptingDrives():
        sys.exit(0)

    for baynum in range(1, bay.maxBays() + 1):
        try:
            pid = os.fork()
        except OSError, e:
            result = 1
            # For a fork failure, append -1 to keep the PID list one-to-one
            # with respect to bays, so each PID refers to bay (list index + 1)
            pids.append(-1)
            syslog.syslog(syslog.LOG_ERR, "Fork error %s locking bay%s" %
                          (e.errno, baynum))
            continue
        if (pid != 0):
            # Parent process
            pids.append(pid)
            continue
        else:
            # Child process
            exit(sed.lock_bay(baynum))
    for index, pid in enumerate(pids):
        # Only get status from children who were actually forked
        if (pid > 0):
            status = os.waitpid(pid, 0)[1]
            if (os.WIFEXITED(status)):
                ret = os.WEXITSTATUS(status)
                if ret not in [sed.SED_RESULT_SUCCESS,
                    sed.SED_RESULT_DRIVE_UNOWNED]:
                    result = 1
                    syslog.syslog(syslog.LOG_ERR,
                                 "failed to lock bay %s (%s)" %
                                 (index + 1, sed.result2str(ret)))
            else:
                    syslog.syslog(syslog.LOG_ERR,
                                  "failed to lock bay %s: "
                                  "child (pid %s) terminated: status %s" %
                                  (index + 1, pid, status))
                    result = 1

    sys.exit(result)

if __name__ == '__main__':
    main()
