#!/usr/bin/python

import sys

file = "/etc/raddb/userlist"

f = open(file)
parsed_file = [[]]
counter = 0
for x in f.xreadlines():
    if x == '\n':
        parsed_file.append([])
        counter+=1
        continue
    number = -1
    if x.endswith('\n\n'): number = -2
    parsed_file[counter].append(x[:number])

data_hash = {}
for x in sys.stdin.read().split('&'):
    tmp_line = x.split('=')
    if len(tmp_line) == 2:
        data_hash[tmp_line[0]] = tmp_line[1]
if not data_hash.has_key('button'):
    data_hash['button'] = ''

if data_hash['button'] == 'Add':
    tmp_array = ["%s\tPassword=\"%s\"" % (data_hash['user'], data_hash['pass'])]
    tmp_array.append("\tSession-Timeout = %s," % data_hash['sess'])
    tmp_array.append("\tIdle-Timeout = %s," % data_hash['idle'])
    tmp_array.append("\tFall-Through = 1")
    parsed_file.append(tmp_array)
elif data_hash['button'] == 'Delete':
    tmp_delete = data_hash['count'].split('\0')
    tmp_delete.reverse()
    for i in tmp_delete:
        del parsed_file[int(i)]

print "Content-type: text/html\n\n"
print "<html><head><title>Radius</title></head>"
print "<body>"

print "<form method=\"post\">"
print "<table>"
counter = 0
for x in parsed_file:
    print "<tr>"
    print "<td><input type=\"checkbox\" name=\"count\" value=\"%s\"></td>" % counter
    print "<td>"
    for y in x:
        print "%s<br>" % y
    print "</td></tr>"
    counter += 1
    print "<tr><td></td>"
print "<td>Username: <input name=\"user\"><br>Password: <input name=\"pass\"><br>Session-Timeout: <input name=\"sess\"><br>Idle-Timeout: <input name=\"idle\"></td></tr>"
print "<tr><td><input type=\"submit\" name=\"button\" value=\"Add\"></td><td><input type=\"submit\" name=\"button\" value=\"Delete\"></td></tr>"
print "</table>"
print "</form>"

f = open(file, "w")
for x in parsed_file:
    for y in x:
        f.write('%s\n' % y)
    f.write('\n')

#commands.getstatusoutput("killall -HUP radiusd")

print "</body></html>"
