#!/usr/bin/python
# -*- coding: utf-8 -*-
### BEGIN LICENSE
# Copyright (C) 2013 Emilien Klein <emilien _PLUS_ debian _AT_ klein _DOT_ st>
# 
# 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 3 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 warranties of 
# MERCHANTABILITY, SATISFACTORY QUALITY, 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, see <http://www.gnu.org/licenses/>.
### END LICENSE

# This script is a wrapper around tryton-client.
# If a config and/or a profiles file wasn't found, it will create new default
# files that are configured for a GNU Health (Tryton) server running on the same
# machine.
# In case the server is not on the same machine, the user will have to change
# the server name during the first startup, but port number, database name and
# user will already be defaulted in.
# After the default files are created, or if those files already exist,
# tryton-client will be run.

import os
import subprocess
import shutil

if __name__ == "__main__":
    #TODO: detect installed version of Tryton automatically
    tryton_version = "3.0"
    base_config_path = os.path.expanduser("~/.config/tryton/%s/" % tryton_version)
    config_file = os.path.join(base_config_path, "tryton.conf")
    default_config_file = "/etc/gnuhealth/gnuhealth-client.tryton.conf"
    profiles_file = os.path.join(base_config_path, "profiles.cfg")
    default_profiles_file = "/etc/gnuhealth/gnuhealth-client.profiles.cfg"

    # Check if there already is a config file
    if not os.path.isfile(config_file):
        # Create the config directory if it doesn't exist
        if not os.path.exists(base_config_path):
            os.makedirs(base_config_path)
        # Copy the default config file
        shutil.copyfile(default_config_file, config_file)
        # Make sure permissions are set appropriately
        os.chmod(config_file, 0644)
    # Check if there already is a profiles file
    if not os.path.isfile(profiles_file):
        # Copy the default profiles file
        shutil.copyfile(default_profiles_file, profiles_file)
        # Make sure permissions are set appropriately
        os.chmod(profiles_file, 0644)

    # Call the Tryton client
    #TODO: pass the arguments given to gnuhealth-server to tryton-server
    args = ["tryton-client"]
    subprocess.Popen(args)

