1/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
2
3/**
4 * @copyright 2013 Couchbase, Inc.
5 *
6 * @author Sarath Lakshman  <sarath@couchbase.com>
7 *
8 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
9 * use this file except in compliance with the License. You may obtain a copy of
10 * the License at
11 *
12 *  http://www.apache.org/licenses/LICENSE-2.0
13 *
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
16 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
17 * License for the specific language governing permissions and limitations under
18 * the License.
19 **/
20
21#include "config.h"
22#include "../view_group.h"
23#include "../util.h"
24
25#include <platform/cb_malloc.h>
26#include <stdio.h>
27#include <stdlib.h>
28#include <string.h>
29#include <inttypes.h>
30#include "util.h"
31#include "../mapreduce/mapreduce.h"
32
33#define BUF_SIZE 8192
34
35int main(int argc, char *argv[])
36{
37    view_group_info_t *group_info = NULL;
38    uint64_t purge_count;
39    int ret = 2;
40    uint64_t header_pos;
41    view_error_t error_info = {NULL, NULL};
42    cb_thread_t exit_thread;
43
44    (void) argc;
45    (void) argv;
46
47    /*
48     * Disable buffering for stdout/stderr
49     */
50    setvbuf(stdout, (char *) NULL, _IONBF, 0);
51    setvbuf(stderr, (char *) NULL, _IONBF, 0);
52
53    if (set_binary_mode() < 0) {
54        fprintf(stderr, "Error setting binary mode\n");
55        goto out;
56    }
57
58    group_info = couchstore_read_view_group_info(stdin, stderr);
59    if (group_info == NULL) {
60        ret = COUCHSTORE_ERROR_ALLOC_FAIL;
61        goto out;
62    }
63
64    ret = start_exit_listener(&exit_thread, 1 /*uses_v8*/);
65    if (ret) {
66        fprintf(stderr, "Error starting stdin exit listener thread\n");
67        goto out;
68    }
69
70    mapreduce_init();
71    ret = couchstore_cleanup_view_group(group_info,
72                                        &header_pos,
73                                        &purge_count,
74                                        &error_info);
75    mapreduce_deinit();
76
77    if (ret != COUCHSTORE_SUCCESS) {
78        if (error_info.error_msg != NULL && error_info.view_name != NULL) {
79            fprintf(stderr,
80                    "Error cleaning up index for view `%s`, reason: %s\n",
81                    error_info.view_name,
82                    error_info.error_msg);
83        }
84        goto out;
85    }
86
87    fprintf(stdout, "PurgedCount %" PRIu64 "\n", purge_count);
88
89out:
90    couchstore_free_view_group_info(group_info);
91    cb_free((void *) error_info.error_msg);
92    cb_free((void *) error_info.view_name);
93
94    ret = (ret < 0) ? (100 + ret) : ret;
95    _exit(ret);
96}
97