from Cryptodome.PublicKey import RSA
from Cryptodome.Cipher import PKCS1_OAEP

import base64

import urllib
import urllib2

import sys
import traceback

def load_rsa_key_file(fileName):
  private_key = RSA.import_key(open(fileName).read())
  return PKCS1_OAEP.new(private_key);

def get_args(args):
  if len(args) < 1:
      print "No id"
      return None

  if len(args) < 2:
      print "No url"
      return None

  ext = ""
  if len(args) > 2:
      ext = args[2]

  id = int(args[0])
  url_base = args[1]
  return (id, url_base, ext)

def report(rsa, id, url_base, ext, val):
      try:
          url = url_base + "status-update" + ext + "?door_id=" + str(id) + "&status=" + ("1" if val else "0")
          print " open " + url
          response = urllib2.urlopen(url)

          responseStr = response.read()
          print "Response: " + responseStr
          enc_verify = base64.b64decode(responseStr)

          verify = rsa.decrypt(enc_verify)

          if ext == "":
              verify = base64.b64encode(verify)

          print " verifying with: " + verify

          url = url_base + "verify-status" + ext + "?door_id=" + str(id) + "&verify=" + urllib.quote(verify)
          print " open " + url
          response = urllib2.urlopen(url)
          print " returned: " + response.read()

          return True
      except Exception as e:
          print str(e)
          traceback.print_tb(sys.exc_info()[2])

      return False

if __name__ == "__main__":
  if len(sys.argv) < 2:
    print "No status"
    exit(1)

  args = get_args(sys.argv[2:])
  if args is None:
    exit(1)

  id, url_base, ext = args

  rsa = load_rsa_key_file("private.pem")
  report(rsa, id, url_base, ext, int(sys.argv[1]))
