#!/usr/bin/env python3

# http://inamidst.com/saxo/
# Created by Sean B. Palmer

import os
import saxo

@saxo.command()
def source(arg):
    if not arg:
        return "Show source of a command"
    elif ("." in arg) or ("/" in arg) or ("\x00" in arg):
        return "Not a valid command name"

    github = "https://github.com/sbp/saxo/blob/master/commands/"
    raw = "https://raw2.github.com/sbp/saxo/master/commands/"
    base = saxo.env("base")
    if base is None:
        return "Sorry, this command requires a running bot"
    command = os.path.join(base, "commands", arg)
    if os.path.isfile(command):
        with open(command) as f:
            a = f.read()

        b_page = saxo.request(raw + arg)
        if b_page["status"] != 200:
            return "Sorry, can't find the source"
        b = b_page["text"]

        if a == b:
            return github + arg
        else:
            return github + arg + " (but local file differs)"
    return "No such command"
