#!/usr/bin/env python

from __future__ import absolute_import, print_function

import os
import subprocess
import sys
from tempfile import NamedTemporaryFile

from changes.config import create_app, db
from changes.models.option import ItemOption
from changes.models.repository import Repository


app = create_app()
app_context = app.app_context()
app_context.push()


def get_repo(url):
    repo = Repository.query.filter_by(url=url).first()

    if not repo:
        print("Repository not found")
        sys.exit(1)

    return repo

repo_id = os.environ.get('CHANGES_SSH_REPO')
if not repo_id:
    raise ValueError("No 'CHANGES_SSH_REPO' in environment")

repo = get_repo(repo_id)

options = dict(
    db.session.query(
        ItemOption.name, ItemOption.value
    ).filter(
        ItemOption.item_id == repo.id,
        ItemOption.name.in_([
            'auth.private-key',
            'auth.private-key-file',
        ])
    )
)

command = [
    'ssh',
    # Not supported in all ssh client versions
    # '-o UserAuthorizedKeysFile=/dev/null',
    '-o LogLevel=ERROR',
    '-o StrictHostKeyChecking=no',
    '-o UserKnownHostsFile=/dev/null',
]
if options.get('auth.private-key'):
    f = NamedTemporaryFile()
    f.write(options['auth.private-key'])
    f.close()
    command.append('-i {0}'.format(f.name))
elif options.get('auth.private-key-file'):
    command.append('-i {0}'.format(options['auth.private-key-file']))

command.append('--')

command.extend(sys.argv[1:])

sys.exit(subprocess.call(
    command,
    cwd=os.getcwd(),
    env=os.environ,
    stdout=sys.stdout,
    stderr=sys.stderr,
))
