#!/usr/bin/env python

#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
#


from  qpid.datatypes import uuid4, UUID, parseUUID
import optparse, os.path, sys, string

op = optparse.OptionParser(
    usage="usage: %prog [options] DATADIR",
    description="View or modify cluster store status for broker with data-directory DATADIR")
op.add_option("-d", "--display", default=False, action="store_true", help="display store status." )
op.add_option("-c", "--mark-clean", default=False, action="store_true", help="mark the store as clean." )

class ClusterStoreStatus:
    """Load/save/display store status file"""

    null_uuid=UUID(bytes='\0'*16)

    def __init__(self, file):
        self.file = file
        self.read()

    def read(self):
        f = open(self.file)
        try: self.cluster_id, self.shutdown_id = [parseUUID(string.rstrip(s)) for s in f.readlines()]
        finally: f.close()

    def write(self):
        f = open(self.file,"w")
        try:
            for u in [self.cluster_id, self.shutdown_id]: f.write(str(u)+"\n")
        finally: f.close()

    def status(self):
        if (self.cluster_id == self.null_uuid): return "empty"
        if (self.shutdown_id == self.null_uuid): return "dirty"
        return "clean"

    def __str__(self):
        return "status: %s\ncluster-id: %s\nshutdown_id: %s" % (
            self.status(), self.cluster_id, self.shutdown_id)

    def mark_clean(self):
        self.shutdown_id = uuid4()
        self.write()

def main(argv=None):
    opts, args = op.parse_args(args=argv)
    if len(args) != 1: op.error("incorrect number of arguments")
    try: status = ClusterStoreStatus(args[0]+"/cluster/store.status")
    except Exception,e: print e; return 1
    if opts.display: print status
    if opts.mark_clean: status.mark_clean(); print status
    return 0

if __name__ == "__main__": 
    sys.exit(main())
