#!/usr/bin/python
#
# "Project" a program to a student desktops by running it on the student desktop.
#
# Usage: project_to_student STUDENT COMMAND ARGS
#
# Geometry is screwed up; depends on knowing the geometry on the target desktop!
#
# I made my vnc password world-readable so that this projection would work.
# Better would be for all of the accounts to have different VNC passwords,
# and only the account being projected makes it password world-readable.

VNCDB = "/home/baccala/vnc.db"

import sys
import signal
import subprocess
import sqlite3

conn = sqlite3.connect(VNCDB)

c = conn.cursor()

DISPLAYS = []
NAMES = dict()

# Doesn't do anything to exclude displays that are no longer running.
# They just error out when we try to run the program on them.

SQL_results = c.execute('SELECT display,name FROM Desktops WHERE name != "Teacher" AND name NOT LIKE "%DCPS%"');

student_name = sys.argv[1]
command = ' '.join(sys.argv[2:])

processes = []

for row in SQL_results:
    display = 'osito:' + str(row[0])
    name = row[1].replace(' ','')

    if name == student_name:
    
        process_args = ['sudo', 'su', name, '-c', 'DISPLAY=' + display + ' ' + command]
        processes.append(subprocess.Popen(process_args))

def signal_handler(sig, frame):
    print('You pressed Ctrl+C!')
#    for proc in processes:
#        proc.kill()
    sys.exit(0)

signal.signal(signal.SIGINT, signal_handler)
print('Press Ctrl+C to terminate')
signal.pause()
