#!/usr/bin/env python3

import json
import os
import sys

from anchore_engine.analyzers import malware
from anchore_engine.analyzers.abstract import Analyzer


class MalwareAnalyzer(Analyzer):
    analyzer_name = "malware"
    scanner_classes = [malware.ClamAVRunner]

    def _run(self):
        print("Beginning malware analyzer execution")
        squashtar = os.path.join(self.unpackdir, "squashed.tar")
        if not os.path.exists(squashtar):
            print("Could not find squashtar file at path {}".format(squashtar))
            exit(1)

        output_meta = {"malware": {}}

        # Execute each of the scanners
        for scanner in self.scanner_classes:
            # Instantiate
            scanner_tmp = (
                self.unpackdir
            )  # use the unpack dir as the temp location to ensure there is space
            scan_obj = scanner(
                self.config.get("analyzer_config"), squashtar, tempdir=scanner_tmp
            )

            # Run the scanner
            if scan_obj.enabled:
                print("Malware scanner {} enabled. Starting run".format(scanner.name))
                result = scan_obj.run()
                output_meta["malware"][scanner.name] = json.dumps(result.to_json())
            else:
                print(
                    "Malware scanner {} not enabled in analyzer config. Skipping".format(
                        scan_obj.name
                    )
                )

        print("Analyzer output: {}".format(output_meta))
        return output_meta


if __name__ == "__main__":
    analyzer = MalwareAnalyzer(cmd_args=sys.argv)
    analyzer_output = analyzer.run()
