#!/usr/bin/python
# -*- coding: utf-8 -*-
# Na szybko sklejone by: Zamber (http://zamber.net/)
# Dzięki dla ^filthy za curl'a ;D
# Licencja: GPL

import os
import sys
import getopt

useragent = "cblip 0.01"
user = "user:pass" # uzupełnij login i hasło

if user == "user:pass"
  print " * Ustaw login i hasło w skrypcie!"
  sys.exit(2)

def usage():
  print "Składnia: blip [OPCJA]...\n"
  print "Argumenty:"
  print "  -h, --help            Wyświetla tą pomoc."
  print "  -m, --msg=WIADOMOŚĆ   Wysyła WIADOMOŚĆ na blipa."
  print "  -f, --file=PLIK       Załącza PLIK (graficzny) na blipa."

def inp():
  inp = 0
  while not inp:
    try:
      inp = raw_input(":> ")
    except ValueError: # w sumie nawet nie wiem po co to tu :P
      inp = 0
      print " * Wprowadź coś normalnego, ok ;)?"
  return inp

def exists(file):
  try:
    woot = open(file)
  except IOError:
    exists = 0
  else:
    exists = 1
  return exists

def start():
  try:

    text = ""
    file = ""

    # wysysamy argumenty z komandlajna
    opts, args = getopt.getopt(sys.argv[1:], "hm:f:", ["help", "msg=", "file="])
    for opt, arg in opts:
      if opt in ("-h", "--help"):
        usage()
        sys.exit(1)
      elif opt in ("-m", "--msg"):
        text = arg
      elif opt in ("-f", "--file"):
        file = arg

    # sprawdzamy duperele odnośnie pliku
    if file:
      if exists(file):
        buff = len(file) - 3
        if file[buff:] == "jpg" or file[buff:] == "gif" or file[buff:] == "png" or file[buff:] == "JPG" or file[buff:] == "GIF" or file[buff:] == "PNG":
          print "Załączono img: " + file
        else:
          print " * Zuy typ pliku (ma być jpg, gif albo png)."
          sys.exit(2)
      else:
        print " * Plik nie istnieje!"
        sys.exit(2)

    # sprawdzamy duperele odnośnie wiadomości
    if not text:
      print "Wiadomość na blipa?"
      text = inp()
    else:
      print "Wiadomość:     " + text

    if len(text) > 160:
      diff = len(text) - 160
      print " * Przekroczono limit znaków o %i (%s)." % (diff, text[160:])
      sys.exit(2)

    #curlowanie
    if file:
      cmd = """curl -v -H 'Accept: application/json' -H 'X-Blip-api: 0.02' -A '%s' -u %s -F "update[body]=%s" -F 'update[picture]=@%s' http://api.blip.pl/updates""" % (useragent, user, text, file)
    else:
      cmd = """curl -v -H 'Accept: application/json' -H 'X-Blip-api: 0.02' -A '%s' -u %s -F "update[body]=%s" http://api.blip.pl/updates""" % (useragent, user, text)

    # wysysamy ałtput curl'a
    fi, fo, fe = os.popen3(cmd)
    for i in fe.readlines():
      if i[:4] == "< Lo":
        print "Twój status:   http://blip.pl/s/" + i[35:]
      if i[:4] == "* Au":
        print " * Problem z zalogowaniem się."

  except KeyboardInterrupt:
    print "Baj baj!"
    sys.exit(1)

  except getopt.GetoptError:
    usage()
    sys.exit(2)

if __name__ == '__main__':
    start()
