#!/usr/bin/env python
# Notify via Slack
# Copyright Christian Bryn 2016-2017 <chr.bryn@gmail.com>

#if python.ver == '2':
from __future__ import print_function
#import fileinput
import argparse
import socket
import sys
#import json
import os
import yaml
import logging

from slackup import SlackUp

def main():
    """ Main routine - parses command line and posts to Slack """

    cfg = {}
    parser = argparse.ArgumentParser()

    #parser.add_argument("-v", "--verbose", help="increase output verbosity", action="store_true")
    parser.add_argument("-v", "--verbose", help="increase output verbosity", action="count")
    parser.add_argument("-c", "--channel", help="specify channel to post to")
    parser.add_argument("-t", "--token", help="set token to use")
    #parser.add_argument("-t", "--prefix", nargs='?', const="[ %s ] " % (socket.getfqdn()), help="Prefix - default is the local hostname. Use with no argument for no prefix.", default="")
    parser.add_argument("-u", "--username", help="set Slack username to post as")
    parser.add_argument("-s", "--snippet", help="Post message as attachment/snippet", action="store_true")
    #parser.add_argument("-m", "--message", help="message to post to slack")
    #parser.add_argument("-f", "--file", nargs='?', type=argparse.FileType('r'), default=sys.stdin, help="read message from file or stdin")
    #parser.add_argument("-f", "--file", type=argparse.FileType('r'), default=sys.stdin, help="read message from file or stdin")
    parser.add_argument("-f", "--file", type=argparse.FileType('r'), help="read message from file or stdin")
    #parser.add_argument("message", nargs='?', type=argparse.FileType('r'), default=sys.stdin, help="message to post to slack")
    parser.add_argument("message", nargs='?', default=None, help="message to post to slack")

    args = parser.parse_args()

    if args.verbose:
        print("verbosity turned on")
    if args.channel:
        cfg['slack_channel'] = args.channel
    if args.token:
        cfg['slack_token'] = args.token
    if args.file:
        args.message = args.file.read()
    if not args.message:
        print("No message supplied!")
        sys.exit(1)

    #if cfg['slack_channel'] == '':
    #    print("No channel given!")
    #    sys.exit(1)
    #if cfg['slack_token'] == '':
    #    print("No token supplied!")
    #    sys.exit(1)

    hostname = socket.getfqdn()
    #print(args.message.type)
    print(args.message)
    message = "[ %s ] %s" % (hostname, args.message)
    #message = "[ %s ] %s" % (hostname, args.message.read())

    slack = SlackUp(cfg)

    if args.snippet:
        if not slack.post_attachment(message):
            print("Error: Failed to post message")
            sys.exit(1)
    else:
        if not slack.post(message):
            print("Error: Failed to post message")
            sys.exit(1)

if __name__ == "__main__":
    main()
