/*
 * Copyright (C) 2017 ~ 2017 Deepin Technology Co., Ltd.
 *
 * Author:     Iceyer <me@iceyer.net>
 *
 * Maintainer: Iceyer <me@iceyer.net>
 *
 * 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 3 of the License, or
 * 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, see <http://www.gnu.org/licenses/>.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <linux/hdreg.h>

#include "diskid.h"

int diskid(const char *diskname, unsigned char *id)
{
    char buffer[1024] = {0};
    int fd;
    static struct hd_driveid hd;

    if (geteuid() >  0) {
        printf("ERROR: Must be root to use\n");
        return 1;
    }

    if ((fd = open(diskname, O_RDONLY|O_NONBLOCK)) < 0) {
        printf("ERROR: Cannot open device %s\n", diskname);
        return 1;
    }
    if (!ioctl(fd, HDIO_GET_IDENTITY, &hd)) {
        int offset = 0;
        size_t modlelen= sizeof(hd.model)/sizeof(hd.model[0]);
        strncpy(buffer+offset, (char*)hd.model, modlelen);
        offset += modlelen;
        size_t seriallen= sizeof(hd.serial_no)/sizeof(hd.serial_no[0]);
        strncpy(buffer+offset, (char*)hd.serial_no, seriallen);

        //make md5 of buffer
        MD5_CTX c;
        unsigned char out[MD5_DIGEST_LENGTH];
        MD5_Init(&c);
        MD5_Update(&c, buffer, 1024);
        MD5_Final(out, &c);

        memcpy(id, out, MD5_DIGEST_LENGTH);
        /*
         * memset(id, 0, MD5_DIGEST_LENGTH*2+1);
        for(i=0; i<MD5_DIGEST_LENGTH; i++) {
            char buf[4]={0};
            memset(buf, 0, 4);
            sprintf(buf, "%02x", out[i]);
            memcpy(id, buf, 2);
            id += 2;
        }
        */
    } else if (errno == -ENOMSG) {
        printf("ERROR: No hard disk identification information available\n");
        return 1;
    } else {
        printf("ERROR: HDIO_GET_IDENTITY\n");
        return 1;
    }
    return 0;
}
