#!/usr/bin/python
# zEscrow - aka ecryptfs-escrow-private
# Copyright (C) 2012 Wesley Wiedenmeier
# Authors: Wesley Wiedenmeier <magicalchicken@mail.magicalchicken.dnsdynamic.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import sys
if sys.version_info > (3, 0):
    from gi.repository import Gtk as gtk
else:
    import gtk
import re
import subprocess


class zEscrowClient:
    serverNameEntry = gtk.Entry()
    serverName = "https://zescrow.gazzang.com"
    passwordEntry = gtk.Entry()
    passwordEntry.set_visibility(False)
    finalVBox = gtk.VBox(False, 2)
    mainBox = gtk.VBox(False, 2)
    menuBar = gtk.MenuBar()

    def destroy(self, widget):
        """destroy the window"""
        gtk.main_quit()

    def create_menu(self):
        """create the main menu bar"""
        fileMenu = gtk.Menu()
        fileM = gtk.MenuItem("File")
        fileM.set_submenu(fileMenu)
        helpMenu = gtk.Menu()
        helpM = gtk.MenuItem("Help")
        helpM.set_submenu(helpMenu)
        about_button = gtk.MenuItem("About")
        about_button.connect("activate", self.about)
        helpMenu.append(about_button)
        quit = gtk.MenuItem("Quit")
        quit.connect("activate", self.destroy)
        fileMenu.append(quit)
        self.menuBar.append(fileM)
        self.menuBar.append(helpM)

    def use_script(self, widget):
        """use the zEscrow script and draw the final window"""
        self.serverName = self.serverNameEntry.get_text()
        passwd = self.passwordEntry.get_text()
        pipe = subprocess.Popen(
            ["zEscrow-cli", self.serverName],
            stderr=subprocess.PIPE, stdout=subprocess.PIPE,
            stdin=subprocess.PIPE)
        stdout_value, stderr_value = pipe.communicate(
            self.passwordEntry.get_text().encode('utf-8'))
        output = stdout_value.decode('utf-8')
        errValue = stderr_value.decode('utf-8')
        self.mainBox.destroy()
        self.create_menu()
        self.finalVBox.pack_start(self.menuBar, False, False, 0)
        logoImage = gtk.Image()
        logoImage.set_from_file("/usr/share/zEscrow/gazzang_logo.png")
        self.finalVBox.pack_start(logoImage, False, False, 0)
        okButton = gtk.Button("Ok")
        if pipe.returncode == 0:
            if re.search('^URL:.https:.*$', output, re.M):
                match = re.search('^URL:.https:.*$', output, re.M)
                returnURL = match.group(0)
                if re.search('https:.*$', returnURL):
                    match = re.search('https:.*$', returnURL)
                    returnURL = match.group(0)
                    print (returnURL)
                    finalText = """
Your mount passphrase has been uploaded successfully.
In order to complete the escrow you need to login to openid.
Just click on the link below and sign in. Thank You."""
                    linkText = "\n<a href=\"" + returnURL + \
                        "\">Open ID Login Link</a>"
                    linkLabel = gtk.Label()
                    linkLabel.set_markup(linkText)
                    linkLabel.set_line_wrap(True)
                    finalLabel = gtk.Label(finalText)
                    finalLabel.set_line_wrap(True)
                    self.finalVBox.pack_start(finalLabel, True, True, 0)
                    self.finalVBox.pack_start(linkLabel, True, True, 0)
                    okButton.connect("clicked", self.destroy)
                else:
                    finalText = "An error has occured:\n" + errValue \
                        + "\nPlease try again."
                    finalLabel = gtk.Label(finalText)
                    finalLabel.set_line_wrap(True)
                    self.finalVBox.pack_start(finalLabel, True, True, 0)
                    okButton.connect("clicked", self.draw_main_window)
            else:
                finalText = "An error has occured:\n" + errValue \
                    + "\nPlease try again."
                finalLabel = gtk.Label(finalText)
                finalLabel.set_line_wrap(True)
                self.finalVBox.pack_start(finalLabel, True, True, 0)
                okButton.connect("clicked", self.draw_main_window)
        else:
            finalText = "An error has occured:\n" + errValue \
                + "\nPlease try again."
            finalLabel = gtk.Label(finalText)
            finalLabel.set_line_wrap(True)
            self.finalVBox.pack_start(finalLabel, True, True, 0)
            okButton.connect("clicked", self.draw_main_window)
        self.finalVBox.pack_start(okButton, False, False, 0)
        self.window.add(self.finalVBox)
        self.window.show_all()

    def more_information(self, path):
        """draw the window displaying info text"""
        infoVBox = gtk.VBox(False, 2)
        logoImage = gtk.Image()
        logoImage.set_from_file("/usr/share/zEscrow/gazzang_logo.png")
        infoVBox.pack_start(logoImage, False, False, 0)
        f = open(path, "r")
        mainMessageText = f.read()
        mainMessageText = re.sub("#", "", mainMessageText)
        mainMessage = gtk.Label(mainMessageText)
        mainMessage.set_line_wrap(True)
        mainMessage.set_size_request(515, 375)
        infoVBox.pack_start(mainMessage, False, False, 0)
        okButton = gtk.Button("Ok")
        okButton.connect(
            "clicked", lambda x: infoWindow.destroy())
        infoVBox.pack_start(okButton, False, False, 0)
        infoWindow = gtk.Window()
        infoWindow.set_title("More Information")
        infoWindow.set_border_width(12)
        infoWindow.add(infoVBox)
        infoWindow.show_all()

    def main_info(self, widget, Data=None):
        """call more info with welome text"""
        self.more_information("/usr/share/zEscrow/welcome-text")

    def password_info(self, widget, Data=None):
        """call more info with password text"""
        self.more_information("/usr/share/zEscrow/password-text")

    def about(self, widget):
        """draw the window containing legal information"""
        aboutVBox = gtk.VBox(False, 2)
        logoImage = gtk.Image()
        logoImage.set_from_file("/usr/share/zEscrow/gazzang_logo.png")
        aboutVBox.pack_start(logoImage, False, False, 0)
        aboutLabelText = """
zEscrow - aka ecryptfs-escrow-private
Copyright (C) 2012 Dustin Kirkland <dustin.kirkland@gmail.com>
Copyright (C) 2012 Scot-Irish Lads, LLC
Copyright (C) 2012 Gazzang, Inc.

Authors: Dustin Kirkland <dustin.kirkland@gmail.com>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, version 3 of the License.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""
        aboutLabel = gtk.Label(aboutLabelText)
        aboutLabel.set_line_wrap(True)
        okButton = gtk.Button("Ok")
        aboutVBox.pack_start(aboutLabel, True, True, 0)
        aboutWindow = gtk.Window()
        okButton.connect(
            "clicked", lambda x: aboutWindow.destroy())
        aboutVBox.pack_start(okButton, False, False, 0)
        aboutWindow.set_title("About")
        aboutWindow.add(aboutVBox)
        aboutWindow.set_border_width(12)
        aboutWindow.show_all()

    def draw_main_window(self, widget):
        """draw main window"""
        self.finalVBox.destroy()
        self.create_menu()
        self.mainBox.pack_start(self.menuBar, False, False, 0)
        logoImage = gtk.Image()
        logoImage.set_from_file("/usr/share/zEscrow/gazzang_logo.png")
        self.mainBox.pack_start(logoImage, False, False, 0)
        mainMessageText = """
Welcome to zEscrow,
To get started, select a server and enter your login passphrase.

"""
        mainMessage = gtk.Label(mainMessageText)
        mainMessage.set_line_wrap(True)
        self.mainBox.pack_start(mainMessage, True, True, 0)
        entryTable = gtk.Table(2, 7, True)
        help_image = gtk.Image()
        help_image.set_from_file("/usr/share/zEscrow/help.png")
        help_image2 = gtk.Image()
        help_image2.set_from_file("/usr/share/zEscrow/help.png")
        serverNameEntryMessage = "zEscrow server:"
        serverNameEntryLabel = gtk.Label(serverNameEntryMessage)
        entryTable.attach(serverNameEntryLabel, 0, 2, 0, 1)
        eventBox1 = gtk.EventBox()
        eventBox1.add(help_image)
        eventBox1.connect("button_press_event", self.main_info)
        entryTable.attach(eventBox1, 2, 3, 0, 1)
        self.serverNameEntry.set_text(self.serverName)
        entryTable.attach(self.serverNameEntry, 3, 7, 0, 1)
        passwordAskingLabelText = "Login passphrase:"
        passwordAskingLabel = gtk.Label(passwordAskingLabelText)
        entryTable.attach(passwordAskingLabel, 0, 2, 1, 2)
        eventBox2 = gtk.EventBox()
        eventBox2.add(help_image2)
        eventBox2.connect("button_press_event", self.password_info)
        entryTable.attach(eventBox2, 2, 3, 1, 2)
        entryTable.attach(self.passwordEntry, 3, 7, 1, 2)
        self.mainBox.pack_start(entryTable, True, True, 0)
        buttonsTable = gtk.Table(1, 2, True)
        startButton = gtk.Button("Upload")
        startButton.connect("clicked", self.use_script)
        buttonsTable.attach(startButton, 0, 1, 0, 1)
        quitButton = gtk.Button("Quit")
        quitButton.connect("clicked", self.destroy)
        buttonsTable.attach(quitButton, 1, 2, 0, 1)
        self.mainBox.pack_start(buttonsTable, False, False, 0)
        self.window.connect("destroy", self.destroy)
        self.window.set_title("zEscrow Client Gtk Frontend")
        self.window.set_border_width(12)
        self.window.add(self.mainBox)
        self.window.show_all()

    def __init__(self):
        """initiate and call func to draw main window"""
        self.window = gtk.Window()
        icon_path = "/usr/share/zEscrow/key_64.png"
        self.window.set_icon_from_file(icon_path)
        self.draw_main_window(gtk.Window())

    def main(self):
        """call main"""
        gtk.main()

if __name__ == "__main__":
    """define main"""
    client = zEscrowClient()
    client.main()
