# -*- coding: utf-8 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4

# Copyright (c) 2012, 2024 dput authors
#
# 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.
"""
Common functions for SSH-based uploaders
"""

import os
import paramiko
import pwd

from dput.exceptions import UploadException


def get_ssh_config(fqdn):
    config = paramiko.SSHConfig()
    if os.path.exists('/etc/ssh/ssh_config'):
        with open('/etc/ssh/ssh_config') as f:
            config.parse(f)
    if os.path.exists(os.path.expanduser('~/.ssh/config')):
        with open(os.path.expanduser('~/.ssh/config')) as f:
            config.parse(f)
    return config.lookup(fqdn)


def find_username(conf, ssh_conf):
    """
    Given a profile (``conf``) and an SSH configuration (``ssh_conf``),
    return the preferred username to login with.
    The profile takes precedence over the SSH configuration.
    It falls back to getting the logged in user's name.
    """
    user = None
    user = pwd.getpwuid(os.getuid()).pw_name
    if 'user' in ssh_conf:
        user = ssh_conf['user']
    if 'login' in conf:
        new_user = conf['login']
        if new_user != '*':
            user = new_user
    if not user:
        raise UploadException(
            "No user to upload could be retrieved. "
            "Please set 'login' explicitly in your profile"
        )
    return user
