#!/usr/bin/env python
#
# Copyright (c) 2003 Marcus Williams <marcus@quintic.co.uk>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
#
# Implements a simple nonce algorithm
#
# Usage: ./nonce.py --create [n]   Creates a new key id for use n times. No
#                                  number means once
#                   --check <key>  Checks a key id if it can be used.
#
# Exit conditions are set up for use with bouncesaying (0 means bounce
# 1 means no bounce).
#
# To use with qmail add two .qmail files:
#
# .qmail-user:
#
# | /var/qmail/bin/bouncesaying "No such user at this address"
#
# .qmail-user-default
#
# | /var/qmail/bin/bouncesaying "Reason for bounce" /path/to/nonce.py --check "$EXT"
# ./Maildir/
#
# Create a key and then mail user-keyid@yourdomain to test.
#
# The latest version of nonce.py can be found at http://www.thesafebox.com

"""
  noonce.py - a simple nonce algorithm

  Usage: ./nonce.py --create [n]   Creates a new key id for use n times.
                                   No number means once
                    --check <key>  Checks a key id if it can be used.
"""
import os
import sys
import stat
import glob
import time
import string
import re

__version__ = "0.2"

HOME=os.path.expanduser('~')
KEYDIR="%s/.keys" % HOME
EXIT=1

def usage():
  print __doc__

if len(sys.argv)<2:
  usage()
  sys.exit(0)

if not os.path.exists(KEYDIR):
  os.mkdir(KEYDIR)
  os.chmod(KEYDIR, stat.S_IRWXU)

if sys.argv[1]=="--create":
  if len(sys.argv)==2:
    n=1
  else:
    n=sys.argv[2]

  t=("%d" % time.time())
  pid=os.getpid()

  while len(glob.glob("%s/%s.%s.*" % (KEYDIR,t,pid))):
    t=("%d" % time.time())
     
  f = os.open("%s/%s.%s.%s" % (KEYDIR, t, pid, n), os.O_WRONLY | os.O_CREAT,0600)
  os.close(f)

  print "%s.%d" % (t, pid)
elif sys.argv[1]=="--check":
  if len(sys.argv)==2:
    usage()
    sys.exit(0)

  # make sure key is all numbers and one digit
  cre=re.compile("[0-9]+\.[0-9]+")
  mtch=cre.match(sys.argv[2])

  if mtch==None:
    EXIT=0
  else:  
    if len(glob.glob("%s/%s.*" % (KEYDIR,sys.argv[2])))==0:
      EXIT=0
    else:
      # file exists but has a count
      files=glob.glob("%s/%s.*" % (KEYDIR,sys.argv[2]))

      # always 1 file
      count = string.atoi(files[0].split(".")[-1])

      os.unlink(files[0])

      count = count-1

      if count<0:
        EXIT=0
      else:
        f = os.open("%s/%s.%d" % (KEYDIR,sys.argv[2],count), os.O_WRONLY | os.O_CREAT,0600)
        os.close(f)

sys.exit(EXIT)

