#!/usr/bin/python
#
# Authors:
# Mustafa Ocak
# muo@uio.no
#
# Copyright (c) 2015 USIT-University of Oslo
#
# This script initialize zabbix-cli environment. it will copy
# /etc/zabbix-cli/zabbix-cli.conf to $HOME/.zabbix-cli/ and change log
# configuration in zabbix-cli.conf so that zabbix-cli logs to
# $HOME/.zabbix-cli/
#
###########################################################################################

from os import getenv,path,remove,close,makedirs
from tempfile import mkstemp
from shutil import move, copy2
import sys

def replace(file_path, pattern, subst):

    #
    #  changing the line having log configuration option 
    #  replacing 
    #  log_file=/var/log/zabbix-cli/zabbix-cli.log
    #  to log_file=~/.zabbix-cli/zabbix-cli.log
    
    try:

        #Create temp file
        fh, abs_path = mkstemp()
        with open(abs_path,'w') as new_file:
            with open(file_path) as old_file:
                for line in old_file:
                    new_file.write(line.replace(pattern, subst))
        close(fh)
        #Remove original file
        remove(file_path)
        #Move new file
        move(abs_path, file_path)

    except Exception as e:
        print '\n[ERROR]: %s\n',e

if __name__ == "__main__":

    zabbixconfdir = getenv('HOME')+"/.zabbix-cli/"
    defconf="/etc/zabbix-cli/zabbix-cli.conf"
    filename="zabbix-cli.conf"

    file_path=path.join(zabbixconfdir,filename)

    try:
        if len(sys.argv) == 2:
            zabbix_api_url = sys.argv[1]
            
        else:
            print "Error: Wrong number of parameters"
            print 'Format: ' + sys.argv[0] + ' <zabbix API url>'        
            sys.exit(1)

    except Exception as e:
        print e
        sys.exit(1)

    #
    # creating ~/.zabbix-cli folder if not exists
    #

    if not path.exists(zabbixconfdir):

        try:
            makedirs(zabbixconfdir)
        except Exception as e:
            print '\n[ERROR]: %s\n',e

    #
    # /etc/zabbix-cli.conf will be created under installation of
    # zabbix-cli package.  copying /etc/zabbix-cli.conf file to
    # ~/.zabbix-cli/zabbix-cli.conf
    # 

    if path.isfile(defconf):
        try:
            copy2(defconf,zabbixconfdir)

        except Exception as e:
            print '\n[ERROR]: %s\n',e
    else:
        print "Cannot find /etc/zabbix-cli/zabbix-cli.conf file. ERROR with zabbix-cli installation."
        sys.exit(1)
    
    #
    #  changing the line having log configuration option 
    #  replacing log file option 
    #  log_file=/var/log/zabbix-cli/zabbix-cli.log
    #  to log_file=~/.zabbix-cli/zabbix-cli.log
    #
    replace(file_path,'log_file=/var/log/zabbix-cli/zabbix-cli.log','log_file=' + getenv('HOME') + '/.zabbix-cli/zabbix-cli.log')

    #
    #  Changing the line having the zabbix API url example with real
    #  URL.
    #
    replace(file_path,';zabbix_api_url=https://zabbix.example.net/zabbix','zabbix_api_url=' + zabbix_api_url)
