#!/usr/bin/env python

'''
Will create links and modify files to embed CamPY in LinuxCNC
should work with any linux distro

usage :
    sudo python CamPY_setup.py [c]

    w/ argument c will restore files and delete links
    w/o argument will create links and modify files

DO NOT USE IN ANY WAYS AFTER CAMPY IS INTEGRATED WITH LINUXCNC DISTRIBUTION

Created on 2016-10-08

@author: Fernand Veilleux
edited by bogie6040 for use with CamPY
'''


prereq = False
import apt
cache = apt.Cache()
if cache['qv4l2'].is_installed:
  	print "qv4l2 is installed"
else:
 	print "qv4l2 NOT INSTALLED!"
	prereq = True

if cache['python-opencv'].is_installed:
  	print "python-opencv is installed"
else:
 	print "python-opencv NOT INSTALLED!"
	prereq = True

if cache['v4l-utils'].is_installed:
  	print "v4l-utils is installed"
else:
 	print "v4l-utils NOT INSTALLED!"
	prereq = True

if cache['v4l2ucp'].is_installed:
  	print "v4l2ucp is installed"
else:
 	print "v4l2ucp NOT INSTALLED!"
	prereq = True

if prereq:
	print ""
	print('One or more required packages are not installed, commands are in CamPY_READ.ME')
	print ""
	exit(1)
print ""

import sys
import os

try :
    from lxml import etree
except :
    print('python-lxml required, command is in CamPY_READ.ME')
    exit(1)


lcode = os.getenv('LANGUAGE', 'en')[0:2]
# print lcode

if "c" in sys.argv[1:] :
    cls = True
else :
    cls = False

print 'wait, processing...'

find = os.popen("find /usr -name 'hal_pythonplugin.py'").read()
if find > '' :
    for s in find.split() :
        s = s.rstrip('\n')
        if not os.path.islink(s) :
            f = open(s).read()
            if cls :
                if f.find('from camview import CamView') >= 0:
                    open(s, "w").write(f.replace('from camview import CamView', ''))
                    print('"from camview import CamView" removed from %s\n' % s)
            else :
                if f.find('from camview import CamView') == -1:
                    open(s, "w").write('from camview import CamView\n' + f)
                    print('"from camview import CamView" added to %s\n' % s)
                else :
                    print('"from camview import CamView" already exists in %s\n' % s)

        head, fn = os.path.split(s)

        fn = os.path.join(head, 'camview.py')
        if os.path.islink(fn) :
            if cls :
                os.remove(fn)
                print 'removed link to camview.py from ', head, '\n'
            else :
                print 'link to camview.py already exists in ', head, '\n'
        elif not cls :
            os.symlink(os.path.join(os.getcwd(), 'camview.py'), fn)
            print 'created link to camview.py in ', head, '\n'

        sd = os.path.join(head, 'path2camview')
        if os.path.isfile(sd) :
            os.remove(sd)
            print 'removed path2camview file'
#        if not cls :
#            open(sd, "w").write(os.getcwd())
#            print 'created path2camview file'

else :
    print 'Directory of "hal_pythonplugin.py" not found - EXITING'
    exit(2)


edited = False
find = os.popen("find /usr -name 'hal_python.xml'").read()
if find > '' :
    for s in find.split() :
        s = s.rstrip('\n')
        if not os.path.islink(s) :
            xml = etree.parse(s)
            root = xml.getroot()
            dest = root.find('glade-widget-classes')
            if cls :
                for n in dest.findall('glade-widget-class'):
                    if n.get('name') == 'CamView':
                        dest.remove(n)
                        edited = True
                        print('glade-widget-class named CamView removed from %s\n' % s)
                        break
            else :
                classfounded = False
                for n in dest.findall('glade-widget-class'):
                    if n.get('name') == 'CamView':
                        classfounded = True
                        print('glade-widget-class named CamView already exists in %s\n' % s)
                        break
                if not classfounded :
                    elem = etree.fromstring('''
<glade-widget-class name="CamView" generic-name="camview" title="Cam View">
            <properties>
                <property id="size" query="False" default="1" visible="False"/>
                <property id="spacing" query="False" default="0" visible="False"/>
                <property id="homogeneous" query="False" default="0" visible="False"/>
            </properties>
        </glade-widget-class> \n

''')
                    dest.insert(0, elem)
                    edited = True
                    print('glade-widget-class named CamView added to %s\n' % s)


            dest = root.find('glade-widget-group')
            if cls :
                for n in dest.findall('glade-widget-class-ref') :
                    if n.get('name') == 'CamView':
                        dest.remove(n)
                        edited = True
                        print('glade-widget-class-ref name CamView removed from %s\n' % s)
                        break
            else :
                classfounded = False
                for n in dest.findall('glade-widget-class-ref'):
                    if n.get('name') == 'CamView':
                        classfounded = True
                        print('glade-widget-class-ref named CamView already exists in %s' % s)
                        break
                if not classfounded :
                    dest.insert(0, etree.fromstring('<glade-widget-class-ref name="CamView"/>'))
                    edited = True
                    print('glade-widget-class-ref named CamView added to %s\n' % s)

            if edited :
                xml.write(s, pretty_print = True)
                print s, 'saved'

else :
    print 'File "hal_python.xml" not found - EXITING'
    exit(3)

if cls :
    # remove link to translation file
    pass
else :
    # add link to translation files
    pass

exit(0)
