#!/usr/bin/python3
# -*- coding: utf-8 -*-
#
#  Copyright (c) 2014,2022 Samuel Degrande
#
#  This file is part of Freedroid
#
#  Freedroid 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.
#
#  Freedroid 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 Freedroid; see the file COPYING. If not, write to the
#  Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
#  MA  02111-1307  USA
#

#
# Get transifex credentials from user's .transifexrc
#
# Code based on the old python txlib (transifex-client written in python)
#

import os
import argparse
import configparser

class ProjectNotInit(Exception):
    pass

def find_dot_tx(path=os.path.curdir, previous=None):
    """Return the path where .tx folder is found.

    The 'path' should be a DIRECTORY.
    This process is functioning recursively from the current directory to each
    one of the ancestors dirs.
    """
    path = os.path.abspath(path)
    if path == previous:
        return None
    joined = os.path.join(path, ".tx")
    if os.path.isdir(joined):
        return path
    else:
        return find_dot_tx(os.path.dirname(path), path)

def _get_tx_dir_path():
    root_path = find_dot_tx()
    if not root_path:
        msg = "Cannot find any .tx directory!"
        raise ProjectNotInit(msg)
    return root_path

def _get_config_file_path(root_path):
    """Check the .tx/config file exists."""
    config_file = os.path.join(root_path, ".tx", "config")
    if not os.path.exists(config_file):
        msg = "Cannot find the config file (.tx/config)!"
        raise ProjectNotInit(msg)
    return config_file

def _read_config_file(config_file):
    """Parse the config file and return its contents."""
    config = configparser.ConfigParser()
    try:
        config.read(config_file)
    except Exception as err:
        msg = "Cannot open/parse .tx/config file: %s" % err
        raise ProjectNotInit(msg)
    return config

def _get_transifex_file(directory=None):
    """Fetch the path of the .transifexrc file.
       It is in the home directory of the user by default.
    """
    if directory is not None:
        return os.path.join(directory, ".transifexrc")

    directory = os.path.expanduser('~')
    txrc_file = os.path.join(directory, ".transifexrc")
    if not os.path.exists(txrc_file):
        return None
    return txrc_file

def _get_transifex_config(txrc_file):
    """Read the configuration from the .transifexrc file."""
    txrc = configparser.ConfigParser()
    try:
        if txrc_file:
            txrc.read(txrc_file)
    except Exception as e:
        print("Cannot read .transifex file: %s." % e)

    return txrc

def get_host_credentials(txrc, host):
    """
    Read .transifexrc and report user,pass for a specific host else ask the
    user for input.
    """
    try:
        username = txrc.get(host, 'username')
        passwd = txrc.get(host, 'password')
        rest_hostname = txrc.get(host, 'rest_hostname')
        token = txrc.get(host, 'token')
    except (ConfigParser.NoOptionError, ConfigParser.NoSectionError):
        username = None
        passwd = None

    return username, passwd, rest_hostname, token

#======================================

def main():
    arg_parser = argparse.ArgumentParser(description='Choose one option')
    arg_parser.add_argument('-u', '--user', action='store_true')
    arg_parser.add_argument('-p', '--password', action='store_true')
    arg_parser.add_argument('-r', '--rest_hostname', action='store_true')
    arg_parser.add_argument('-t', '--token', action='store_true')
    args = arg_parser.parse_args()
    
    try:
        root = _get_tx_dir_path()
        config_file = _get_config_file_path(root)
        config = _read_config_file(config_file)
        host = config.get('main', 'host')
        txrc_file = _get_transifex_file()
        if not txrc_file :
        	return
        txrc = _get_transifex_config(txrc_file)
    except ProjectNotInit as e:
        print(unicode(e))
        return

    username, password, rest_hostname, token = get_host_credentials(txrc, host)
    if args.user and username:
        print(username)
    if args.password and password:
        print(password)
    if args.rest_hostname and rest_hostname:
        print(rest_hostname)
    if args.token and token:
        print(token)

if __name__ == "__main__":
    main()
