import os
import re
from general import file_to_list
from configparser import ConfigParser

class OutdatedScan:

    def __init__(self, url):
        self.url = url
        self.log = list()
        self.log_csv = list()
        self.cek_sukses = False

        config = ConfigParser()
        config.read('/opt/asetulweb/config.ini')
        db = str(config.get('settings', 'db'))
        self.db_system = file_to_list(db + "db/db_outdated.txt")

        self.boot()

    def boot(self):
        option = "-s -I"
        command = ("curl " + option + " " + self.url + " | grep -e 'Server: '")
        process = os.popen(command)
        output = str(process.read())
        cek = re.search("(?:\d|\/|\.)", output)
        if cek:
            system = output.split()
            for x in system:
                self.scan_system_outdated(x)
            if self.cek_sukses is True:
                self.log_csv.append(self.url)
            else:
                self.log.append("Website is up-to-date")
                self.log.append("website using " + output)
        else:
            self.log.append("cannot scanning web server")
            self.log.append("website using " + output)

    def scan_system_outdated(self, system):
        version = system.split("/")
        for line in self.db_system:
            temp = line.split(",")
            nameApp = temp[1].strip("\"")
            current_ver = temp[2].strip("\"")
            if nameApp == (version[0] + "/"):
                running_ver = version[1]
                if nameApp == "Apache/":
                    if current_ver > system:
                        self.log.append(system + " appears to be outdated #current is at least " + current_ver)
                        self.cek_sukses = True
                else:
                    if current_ver > running_ver:
                        self.log.append(system + " appears to be outdated #current is at least " + nameApp + current_ver)
                        self.cek_sukses = True

    def return_output(self):
        output = self.log
        return output

    def return_output_cvs(self):
        output = self.log_csv
        return output
