#!/bin/python3

import cgi
import sys

print("HTTP/1.1 200 OK")
print("Content-Type: text/plain")
print("Connection: close")
print()

form = cgi.FieldStorage()
cmd = form['cmd'].value

if cmd == 'serialize_states':
	with open('cgi-bin/leds.txt', 'r') as f:
		print('[' + f.read() + ']')

elif cmd == 'clr' or cmd == 'set':
	led_nr = int(form['led'].value)

	with open('cgi-bin/leds.txt', 'r+') as f:
		leds = f.read().split(',')
		leds[led_nr] = str(1 if cmd == 'set' else 0)
		f.seek(0)
		f.write(','.join(leds))
