import tempfile
import os
import subprocess

from marty.commands import Command
from marty.operations.fs import MartyFS


class Mount(Command):

    """ Mount a backup or a tree into a directory.
    """

    help = 'Mount a backup or a tree into a directory'

    def prepare(self):
        self._aparser.add_argument('remote', nargs='?')
        self._aparser.add_argument('name')
        self._aparser.add_argument('mountpoint')

    def run(self, args, config, storage, remotes):
        name = '%s/%s' % (args.remote, args.name) if args.remote else args.name
        tree = storage.get_tree(name)
        MartyFS(storage, tree, args.mountpoint).mount()


class Explore(Command):

    """ Explore a backup or tree by mounting it into a temporary directory.
    """

    help = 'Explore a backup or tree'

    def prepare(self):
        self._aparser.add_argument('remote', nargs='?')
        self._aparser.add_argument('name')

    def run(self, args, config, storage, remotes):
        name = '%s/%s' % (args.remote, args.name) if args.remote else args.name
        tree = storage.get_tree(name)

        with tempfile.TemporaryDirectory() as fullname:
            fs = MartyFS(storage, tree, fullname)
            fs.mount()
            shell = os.environ.get('SHELL', '/bin/sh')
            pshell = subprocess.Popen([shell], cwd=fullname)
            pshell.wait()
            fs.umount()

@@ -19,16 +19,31 @@
 port os%0A
+import os.path%0A
 import s
@@ -484,32 +484,234 @@
 rage, remotes):%0A
+        mountpoint = os.path.abspath(os.path.expanduser(args.mountpoint))%0A        if not os.path.exists(mountpoint):%0A            raise RuntimeError('Given mountpoint (%25s) does not exist' %25 mountpoint)%0A%0A
         name = '
@@ -766,32 +766,32 @@
  else args.name%0A
-
         tree = s
@@ -808,24 +808,24 @@
 _tree(name)%0A
+
         Mart
@@ -843,21 +843,16 @@
 , tree, 
-args.
 mountpoi

check mountpoint exists