/***************************************************************************
 *   Copyright (C) 2004 by Fred Schaettgen <kdebluetooth@schaettgen.de>    *
 *                                                                         *
 *   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.                                   *
 ***************************************************************************/
 
#include <iostream>
#include <string>
#include <errno.h>
#include <sys/socket.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/hci.h>
#include <bluetooth/hci_lib.h>
 
using namespace std;

int main(int argc, char* argv[])
{
    if (argc <= 3 || string(argv[1]) != "auth") {
        cout << "This is a helper program for kbtobexsrv. " << endl;
        cout << "It will send an authentication request for a given ACL link." << endl;
        cout << "Usage: auth-helper auth <hcidev> <connection handle (decimal)>" << endl;
        cout << "Example: auth-helper auth 0 42" << endl;
        cout << "Return values: 1=general error 2=permission denied" << endl;
        exit(1);
    }
    else {
        int hcidev = atoi(argv[2]);
        int connhandle = atoi(argv[3]);
        
        int s = hci_open_dev(hcidev);
        if (s < 0)
        {
            cerr << "auth-helper: hci_open_dev() failed: " << strerror(errno) << endl;
            exit(1);
        }

        auth_requested_cp auth_request;
        auth_request.handle = connhandle;
        int send_error = hci_send_cmd(s, OGF_LINK_CTL, OCF_AUTH_REQUESTED, 
            AUTH_REQUESTED_CP_SIZE, &auth_request);
        int e = errno;
        int ret;
        if (send_error == 0) {
            ret = 0;
        }
        else if (e == EPERM)
        {
            cerr << "auth-helper: authentication request not permitted." << endl;
            ret = 2;        
        } 
        else {
            cerr << "auth-helper: hci_send_cmd() failed: " << strerror(e)
                << "(" << e << ")" << endl;
            ret = 1;
        }
        
        hci_close_dev(s);
        exit(ret);
    }
}
