/*
 * Copyright (C) 2023 Luca Boccassi <bluca@debian.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <unistd.h>

/* From linux/sed-opal.h */
struct opal_status {
    uint32_t flags;
    uint32_t reserved;
};
#define IOC_OPAL_GET_STATUS _IOR('p', 236, struct opal_status)
#define OPAL_FL_SUPPORTED 0x1
#define OPAL_FL_LOCKING_SUPPORTED 0x2

static inline void closep(int *fd) {
    if (!fd || *fd < 0)
        return;

    close(*fd);
    *fd = -1;
}

int main(int argc, char **argv) {
    struct opal_status st = { };
    __attribute__((__cleanup__(closep))) int fd = -1;
    int r;

    if (argc < 2) {
        printf("Missing argument.\nUsage: %s device\n", argv[0]);
        return EXIT_FAILURE;
    }

    fd = open(argv[1], O_RDONLY|O_CLOEXEC);
    if (fd < 0) {
        perror("Opening device failed:");
        return EXIT_FAILURE;
    }

    r = ioctl(fd, IOC_OPAL_GET_STATUS, &st);
    if (r < 0) {
        perror("IOC_OPAL_GET_STATUS ioctl failed:");
        return EXIT_FAILURE;
    }

    if (!(st.flags & (OPAL_FL_SUPPORTED|OPAL_FL_LOCKING_SUPPORTED)))
        return EXIT_FAILURE;

    return EXIT_SUCCESS;
}
