/*
 * libkarma/chprop.c
 *
 * Copyright (c) Frank Zschockelt <libkarma@freakysoft.de> 2004
 *
 * You may distribute and modify this program under the terms of 
 * the GNU GPL, version 2 or later.
 *
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>

#include <lkarma.h>

#define CHECK(x) x?"failed":"ok"

void usage(void);

void usage(void)
{
    printf("usage: chprop -a hostname/ip [-p password] fid key value\n");
}

int main(int argc, char * argv[])
{
    int c;
    int karma;
    char *host=NULL;
    char *p=NULL;
    uint32_t fid;

    while ((c = getopt(argc, argv, "ha:p:s:")) != -1) {
        switch(c) {
            case 'h':
                usage();
                return -1;
                break;
            case 'a':
                host=strdup(optarg);
                break;
            case 'p':
                p=strdup(optarg);
                break;
            case '?':
                printf("unknown arg %c\n", optopt);
                break;
        }
    }
    
    if((!host) ||(optind+3 != argc)){
        usage();
        if(p) free(p);
        return -1;
    }
    
    karma=lk_karma_connect(host);
    free(host);
    
    if(karma < 0){
        usage();
        if(p) free(p);
        return -1;
    }

    lk_properties_init();
    
    if(p){
        printf("lk_karma_authenticate: %i\n", lk_karma_authenticate(karma, p));
        free(p);
    }else printf("lk_karma_authenticate: %i\n",
                 lk_karma_authenticate(karma, ""));
    printf("lk_karma_request_io_lock: %s\n",
           CHECK(lk_karma_request_io_lock(karma,IO_LOCK_W)));
    
    lk_karma_get_device_settings(karma, &p);
    
    lk_karma_load_database(karma);
    
    fid=strtoul(argv[optind], (char **) NULL, 10);
    
    lk_properties_set_property(fid, argv[optind+1], argv[optind+2]);
    p=lk_properties_export(fid);
    printf("lk_karma_update_file_details: %s\n",
           CHECK(lk_karma_update_file_details(karma, fid, p)));
    free(p);
    printf("lk_karma_release_io_lock: %s\n",
           CHECK(lk_karma_release_io_lock(karma))); 
    printf("lk_karma_hangup: %s\n", CHECK(lk_karma_hangup(karma)));
    close(karma);
    lk_properties_destroy();
    return 0;
}
