##
##   lts.conf parser
##
##   Copyright (C) 2007 Canonical Ltd.
##
##   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, 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.

"""
ltsconf reads and writes the lts.conf file for ltsp servers, 
does an automatic backup and has a rollback function to the 
backed up config.

Copyright 2007, Canonical Ltd.
"""

import os
import os.path

def read(path):
    """
    returns an array of triplets (index, key, value) and an index list
    read from lts.conf in path.
    example: data_array,idx=ltsconf_read(./lts.conf)
             print data_array
             [('default', 'SOUND', 'True'),('default','LOCALDEV','True'), ('...]
             print idx
             ['default','00:11:25:84:CE:BA']

    path: full path to lts.conf file
    """

    idx = []
    data_array = []
    if os.path.isfile(path):
        ltsconf = open(path)
        ltsp_data = ltsconf.read().split('\n')
    
        for line in ltsp_data:
            line = line.strip()
            if not line.startswith('#'):
                if line.startswith('['):
                    index = line.strip('[]')
                    idx.append(index)
                else:
                    if line:
                        key = line.split('=')[0]
                        value = line.split('=')[1]
                        data_array.append((index,key,value))
        return data_array, idx

def write(path, data_array, idx):
    """
    writes an lts.conf in path, containing groups listed in idx and values in 
    those groups from data_array. by default path/.lts.conf.bak is created before 
    writing the new file.

    path: full path to an lts.conf file
    data_array: array of triplets [(index,key,value), (index, key2, value2), ...]
    idx: list of indexes [index1, index2, ... ]
    """
    if os.path.isfile(path):
        os.rename(path, path.rstrip('lts.conf')+'.lts.conf.bak')
    ltsconf = open(path, 'w')
    ltsconf.write('###########################################\n')
    ltsconf.write('# AUTOGENERATED FILE, DO NOT EDIT !       #\n')
    ltsconf.write('# Use the thinclient-configurator instead #\n')
    ltsconf.write('# A backup of the last configuration can  #\n')
    ltsconf.write('# be found hidden in the same path, named #\n')
    ltsconf.write('# .lts.conf.bak                           #\n')
    ltsconf.write('###########################################\n')
    for index in idx:
        ltsconf.write('\n['+index+']\n')
        for line in data_array:
            if line[0] == index:
                ltsconf.write('\t'+line[1]+'='+line[2]+'\n')
    return True

def rollback(path):
    """
    rolls back the config from a backed up ltsp configuration if path/.lts.conf.bak
    exists.

    path: full path to an lts.conf file
    """
    if os.path.isfile(path):
        os.rename(path.rstrip('lts.conf')+'.lts.conf.bak', path)
        return True
    return False
