# smbclient.py
#-*- coding:utf-8 -*-
# Copyright (C) 2008 Stefan J. Betz <stefan_betz@gmx.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

"""
==============================
Service Message Block Handling
==============================

All functions in this API rely on smbclient for their real work.
"""

import subprocess
import copy
import re
from pyneighborhood import db, dblock, config

sharere = re.compile("^\t(.*)Disk *(.*)$", re.M)
anonsharelookupcommand = [ "smbclient", "-N", "-L" ]

def scan_shares(ip, manual=False):
    """
    Query all visible shares from `ip`.

    :param ip: IPv4 of host to scan.
    :param manual: ``True`` if this host has been added manually through the user
    :returns: None
    :rtype: None
    """
    manual = 1 if manual else 0
    command = copy.copy(anonsharelookupcommand)
    command.append(ip)
    process = subprocess.Popen(command,
                                executable = command[0],
                                stdout = subprocess.PIPE,
                                stderr = subprocess.STDOUT )
    process.wait()
    output = process.stdout.read()
    match = sharere.search(output)
    cursor = db.cursor()
    host_id = cursor.execute("""SELECT id FROM hosts WHERE ip=?;""", (ip,)).fetchall()
    if host_id:    
        while match:
            sharename = match.group(1).rstrip()
            comment = match.group(2).rstrip()
            result = cursor.execute("""SELECT * FROM shares WHERE name = ? AND host = ?""", (sharename,host_id[0][0])).fetchall()
            if not (sharename.endswith('$') and config.get('Main','hidden_shares') == 'False'):
                if len(result) == 0:
                    dblock.acquire()
                    cursor.execute("""INSERT INTO shares (name,host,comment,manual) VALUES (?,?,?,?);""", (sharename,host_id[0][0],comment, manual))
                    dblock.release()
                elif len(result) == 1:
                    dblock.acquire()
                    cursor.execute("""UPDATE shares SET validated = 1 WHERE id = ?""", (result[0][0],))
                    dblock.release()
            match = sharere.search(output, match.end())
