#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Copyright 2017 Mir Calculate. http://www.calculate-linux.org
#
#  Licensed 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.
import argparse
import sys

from calculate.lib.utils.debug import (
    dump_real_sysfs, dump_real_udev,
    dump_real_lvm,
    dump_real_devfs,DumpError)
from calculate.core.setup_cache import Cache
from calculate.lib.utils.files import (listDirectory, tar_list,
    removeDir, quite_unlink)
from os import path


class ArgumentParserCache(argparse.ArgumentParser):
    def __init__(self):
        super(ArgumentParserCache, self).__init__(
            description="Dump system information")
        self.add_argument('--force', action="store_true",
                          help='skip check mtime')


if __name__ == '__main__':
    apv = ArgumentParserCache()
    args = apv.parse_args()
    prefix = "/tmp/cldump"
    tarfn = "/tmp/cldump.tar.bz2"
    try:
        if path.exists(prefix):
            removeDir(prefix)
        dump_real_sysfs(path.join(prefix, "sysfs.json"))
        dump_real_udev(path.join(prefix, "udev.export"))
        dump_real_devfs(path.join(prefix, "devfs.json"))
        dump_real_lvm(path.join(prefix, "pvdisplay.export"))
        quite_unlink(tarfn)
        tar_list(listDirectory(prefix), tarfn,
                 prefix=prefix)
        removeDir(prefix)
        print("Dump file saved to %s" % tarfn)
    except DumpError as e:
        sys.stderr.write("%s\n" % str(e))
