cps_api_return_code_t cps_api_timeout_wait(int handle, fd_set *r_template, size_t timeout_ms,const char *op) {
    fd_set _rset = *r_template;
    struct timeval tv;
    tv.tv_sec = timeout_ms / 1000;
    tv.tv_usec = MILLI_TO_MICRO(timeout_ms % 1000);    //just the milliseconds portion
    int rc = std_select_ignore_intr(handle+1,&_rset,nullptr,nullptr,&tv,nullptr);
    if (rc==-1) {
        EV_LOG(ERR,DSAPI,0,op,"CPS Operation failed - application close");
        return cps_api_ret_code_ERR;
    }
    if (rc==0) {
        EV_LOG(ERR,DSAPI,0,op,"CPS Operation failed - application time out");
        return cps_api_ret_code_TIMEOUT;
    }
    return cps_api_ret_code_OK;
}
int main(int argc, char**argv) {
    char * path = "/var/run/ar.npu.shell";

    int opt = -1;
    char unit_str[30]="";
    char cmd_str[1024]="";
    char *exit_cmd="\n::exit\n";
    char *prompt_off="\n::prompt:off\n";
    char *prompt_on="\n::prompt:on\n";

    while ((opt=getopt(argc,argv,"u:c:"))!=-1) {
        switch(opt) {
        case 'u':
            snprintf(unit_str,sizeof(unit_str)-1,"::%s\n",optarg);
            break;
        case 'c':
            snprintf(cmd_str,sizeof(cmd_str)-1,"\n\n%s\n",optarg);
            break;
        default:
            printf("Valid args are [ -u unit -c \"cmd\" ]\n");
            exit (1);
        }
    }

    int sock=-1;

    if (std_cmd_redir_connect(path,&sock)!=STD_ERR_OK)
        return -1;
    if (strlen(cmd_str)>0) {
        int rc = std_write(sock,prompt_off,strlen(prompt_off)+1,true,NULL);
        if (rc==-1) return -1;
    } else {
        int rc = std_write(sock,prompt_on,strlen(prompt_on)+1,true,NULL);
        if (rc==-1) return -1;
        printf("Welcome to the NPU Shell\ntype ::exit to exit the shell and ::[npu] to change the default npu\n");
    }
    if (strlen(unit_str)>0) {
        int rc = std_write(sock,unit_str,strlen(unit_str)+1,true,NULL);
        if (rc==-1) return -1;
    }
    if (strlen(cmd_str)>0) {
        int rc = std_write(sock,cmd_str,strlen(cmd_str)+1,true,NULL);
        if (rc==-1) return -1;
    }

    while (true) {
        fflush(stdout);
        struct timeval tv={1,0};
        fd_set rset;
        int selfds[]={STDIN_FILENO,sock};
        int max_fd = -1;
        std_sel_adds_set(selfds,sizeof(selfds)/sizeof(*selfds),
                    &rset,&max_fd,true);

         int rc = std_select_ignore_intr(max_fd+1,&rset,NULL,NULL,&tv,NULL);

        if (rc==0) {
            if (strlen(cmd_str)>0) {
                int rc = std_write(sock,exit_cmd,strlen(exit_cmd)+1,true,NULL);
                if (rc==-1) return -1;
             }
             continue;
        }
        if (rc==-1) break;
        if (FD_ISSET(STDIN_FILENO,&rset)) {
            if ((rc=std_fd_copy(sock,STDIN_FILENO,NULL))==-1 || rc==0) break;
        }
        if (FD_ISSET(sock,&rset)) {
            if ((rc=std_fd_copy(STDOUT_FILENO,sock,NULL))==-1 || rc==0) break;
            fflush(stdout);
        }
    }
    return 0;
}