#!/usr/bin/env python3
#
# Copyright (C) 2012-2017 Chris Cummins.
#
# This file is part of emu.
#
# Emu is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# Emu is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
# License for more details.
#
# You should have received a copy of the GNU General Public License
# along with emu.  If not, see <http://www.gnu.org/licenses/>.
#
from __future__ import print_function

import os
import sys
import subprocess

from emu import *
from emu import io


def main(argv, argc):
    parser = Parser()
    parser.add_option("-d", "--dry-run", action="store_true",
                      dest="dry_run", default=False)
    parser.add_option("-t", "--template-dir", action="store", type="string",
                      dest="template_dir", default=Meta.sink_templates)
    parser.add_option("-f", "--force", action="store_true", dest="force",
                      default=False)
    parser.add_option("-i", "--ignore-errors", action="store_true",
                      dest="ignore_errors", default=False)
    parser.add_option("--no-archive", action="store_true",
                      dest="no_archive", default=False)
    (options, args) = parser.parse_args()

    # Fail if no read/write permissions
    Util.readable(options.source_dir, error=True)
    Util.writable(options.source_dir, error=True)

    source = Source(options.source_dir)

    if len(args) < 1:
        # List sinks:
        for sink in source.sinks():
            print(colourise(sink.name, Colours.GREEN))
            if io.verbose_enabled:
                snapshots = list(sink.snapshots())
                if sink.head():
                    head_id = sink.head().id.snapshot_name
                else:
                    head_id = ""

                command = "df -h '{0}'".format(sink.path)
                device = (subprocess.check_output(command, shell=True)
                          .split("\n")[1].split()[0])

                print("Location:        {0}".format(sink.path))
                print("No of snapshots: {0}".format(len(snapshots)))
                print("Head:            {0}".format(head_id))
                print("Device:          {0}".format(device))

    else:
        command = args.pop(0)

        # Add sinks:
        if command == "add":
            if len(args) == 2:
                name = args[0]
                path = args[1]
            else:
                print("Usage: add <name> <path>")
                sys.exit(1)

            Sink.create(source, name, path, options.template_dir,
                        ignore_errors=options.ignore_errors,
                        archive=not options.no_archive,
                        force=options.force)

        # Remove sinks:
        elif command == "rm":
            if not len(args):
                print("Usage: rm <name ...>")
                sys.exit(1)

            for arg in args:
                try:
                    sink = Util.get_sink_by_name(arg, source.sinks())
                    sink.destroy(force=options.force)
                except SinkNotFoundError as e:
                    print(e)
                    sys.exit(1)

        # Clean sinks:
        elif command == "clean":
            if not len(args):
                print("Usage: clean <name ...>")
                sys.exit(1)

            for arg in args:
                try:
                    sink = Util.get_sink_by_name(arg, source.sinks())
                    sink.clean(dry_run=options.dry_run)
                except SinkNotFoundError as e:
                    print(e)
                    sys.exit(1)

        else:
            print("Invalid command. See: emu sink --help")
            sys.exit(1)

    return 0

if __name__ == "__main__":
    argv = sys.argv[1:]
    ret = main(argv, len(argv))
    sys.exit(ret)
