#!/usr/bin/python
# vim: fileencoding=utf-8
#
# The Qubes OS Project, https://www.qubes-os.org/
#
# Copyright (C) 2016 Marek Marczykowski-Górecki
#                                       <marmarek@invisiblethingslab.com>
#
# This program 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 2 of the License, or
# (at your option) any later version.
#
# This program 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 this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
import argparse
import os
import socket
import subprocess
import sys


def ssh(args):
    assert args[1] == '/bin/sh'
    os.execl('/usr/bin/qrexec-client-vm',
        'qrexec-client-vm', args[0], 'qubes.VMShell')
    return 1


def scp(args):
    assert len(args) == 2 and args[1].count(':') == 1
    src_path = args[0]
    (dst_host, dst_path) = args[1].split(':')
    subprocess.check_call(['qvm-copy-to-vm', dst_host, src_path])
    p = subprocess.Popen(['qrexec-client-vm', dst_host, 'qubes.VMShell'],
        stdin=subprocess.PIPE
    )
    p.communicate('sudo mv "/home/user/QubesIncoming/{}/{}" "{}"\n'.format(
        socket.gethostname(),
        os.path.basename(src_path),
        dst_path
    ))
    if p.returncode != 0:
        raise RuntimeError('Failed to write target file {}'.format(dst_path))
    return 0


def parse_opts(args):
    parser = argparse.ArgumentParser()
    parser.add_argument('-o', action='append', nargs=1)
    parser.add_argument('--version', '-V', action='store_true')
    (opts, args) = parser.parse_known_args(args)
    if opts.version:
        print 'OpenSSH_6.6.1p1 qubes.VMShell wrapper, ' \
              'OpenSSL 1.0.1k-fips 8 Jan 2015'
        sys.exit(0)
    return args


def main(args=None):
    args = parse_opts(args)
    if sys.argv[0].endswith('ssh'):
        return ssh(args)
    elif sys.argv[0].endswith('scp'):
        return scp(args)
    else:
        raise RuntimeError('Unsupported program {} called'.format(sys.argv[0]))

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