#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# OP Desktop Connector Setup v. 4.4 module for Tea4CUPS : Tee for CUPS
# https://fitosoft.com/webhelp/source/connector.htm
#
# (c) 2019 Fitosoft, Inc. <info@fitosoft.com>
# 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.
#

import os
import ssl
import urllib
import urllib2
import base64
import socket
import traceback
import ConfigParser
import getpass
import time
import json
from xml.dom.minidom import parseString
from xml.dom import minidom

# write debug string
def write_debug(st):
    if trace == '1':
        statinfo = os.stat(cupstrace)
        if statinfo.st_size > 100000:
            f = open(cupstrace,'w')
        else:
            f = open(cupstrace,'a')
        f.write('\n' + st)
        f.close()

# parse command line options
try:
	print "-------------------------------------------------------------------------"
	print "OP - Tracks and controls printing activity - https://opcloud.fitosoft.com"
	print "OP Connector's Access Keys ID on https://opcloud.fitosoft.com/users/servers.html"
	name_uid = raw_input("Enter existing OP Connector's Access Key ID: ")
	trace = raw_input("Enable tracing to /etc/cups/op_trace.txt (0 - off, 1 - on) [0]: ")
	exception = raw_input("Enable printing if exception occurred (0 - off, 1 - on) [1]: ")
	prepend_tea4cups = raw_input("Prepend each DeviceURI value for all printers with 'tea4cups://') [Y]: ")

	if (trace == ''):
		trace = '0'

	if (exception == ''):
		exception = '1'

	if (prepend_tea4cups == ''):
		prepend_tea4cups = 'Y'

	query = {'name_uid' : name_uid}

	req = urllib2.Request('https://checkprint.herokuapp.com:443/connectorsettings');
	#req = urllib2.Request('http://192.168.0.21:5000/connectorsettings');
	req.add_header('Content-Type','application/json')
	req.add_header('User-Agent','Mozilla/4.0')
	req.add_data(json.dumps(query))

	context = ssl._create_unverified_context()
	
	r = urllib2.urlopen(req, context=context, timeout=15)
	#r = urllib2.urlopen(req)

	# read query
	data = r.read()
	json_res = json.loads(data)

	if 'error' in json_res:
		print "Error: " + json_res['error']	
		if 'error_details' in json_res:
			print json_res['error_details']	
		os._exit(1)
	
	# save connector settings
	config = ConfigParser.ConfigParser()
	config.add_section('global')
	config.set('global', 'name_uid', name_uid)
	config.set('global', 'trace', trace)
	config.set('global', 'exception', exception)
	if "ImagesIsSave" in json_res:
		config.set('global', 'cnv_is', json_res["ImagesIsSave"])
	if "ImagesType" in json_res:
		config.set('global', 'cnv_type', json_res["ImagesType"])
	if "ImagesSaveType" in json_res:
		config.set('global', 'cnv_image', json_res["ImagesSaveType"])
	if "ImagesSavePagesMaxCount" in json_res:
		config.set('global', 'cnv_maxcount', json_res["ImagesSavePagesMaxCount"])
	if "ImagesSaveQuality" in json_res:
		config.set('global', 'cnv_quality', json_res["ImagesSaveQuality"])
	if "ImagesSaveLongPixelLength" in json_res:
		config.set('global', 'cnv_longpixels', json_res["ImagesSaveLongPixelLength"])
	if "ConnectorVersion" in json_res:
		config.set('global', 'version', json_res["ConnectorVersion"])
   
	with open('/etc/cups/op-cloud-connector.conf', 'wb') as configfile:
		config.write(configfile)

	if prepend_tea4cups == 'Y' or prepend_tea4cups == 'y':
		s = open("/etc/cups/printers.conf").read()
		s = s.replace('tea4cups://', '')
		s = s.replace('DeviceURI ', 'DeviceURI tea4cups://')
		f = open("/etc/cups/printers.conf", 'w')
		f.write(s)
		f.close()

    	print 'Ok\n'
	os._exit(0)

except:
	print traceback.format_exc()
	os._exit(1)


