#!/usr/bin/python
# Copyright (C) 2009-2013 Zentyal S.L.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the Lesser 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
# Lesser GNU General Public License for more details.
#
# You should have received a copy of the Lesser GNU General Public
# License along with This program; if not, write to the
#	Free Software Foundation, Inc.,
#	59 Temple Place, Suite 330,
#	Boston, MA  02111-1307
#	USA

from sys import argv, exit
from glob import glob
from zentyal_pwdsync_common import get_queue_path
import os, re

QUEUE_PATH = get_queue_path()

username = argv[1]
password = argv[2]

# if the username is not going to be valid on Zentyal
# we do not try to send the password change
user_re = re.compile("([a-zA-Z\d\s_-]+\.)*[a-zA-Z\d\s_-]+")
if not user_re.match(username):
    exit(1)

QUEUE_PATH += '/' + username
if not os.access(QUEUE_PATH, os.F_OK):
    os.mkdir(QUEUE_PATH, 0600)
os.chdir(QUEUE_PATH)
existingFiles = glob('*')
lastNum = 0
if existingFiles:
    lastNum = sorted(map(int, existingFiles), reverse=True)[0]
newFile = str(lastNum + 1)
print "Creating file: " + newFile

f = open(newFile, 'w')
f.write(password + '\n')
f.close()
