r'''Create a directory on the server.

'''

from api.exploit import WebshellExploit, Cmdline
from api.webshell import WebshellSession, Webshell
from api import logger, utils
import argparse
import os
import json
import re
import base64

class exploit(WebshellExploit):

    def __init__(self):
        super().__init__()
        self.parse = argparse.ArgumentParser(prog='mkdir', description="Create a directory on the server.")
        self.parse.add_argument('dest', help="A file path on the server.")
        self.parse.add_argument('-m', '--mode', help="Specify an access mode code(only on unix system), like `777`.", type=self._check)
        self.help = __doc__ + self.parse.format_help()

    def _check(self, param: str)->int:
        test = r'[0-7]{3}'
        if re.fullmatch(test, param):
            return int(param, base=8)
        
        raise TypeError(f'The access mode must be a three-digit integer in octal, like `777`')

    def support(self, session:WebshellSession)-> bool:
        '''判断当前命令是否支持指定的session， 一般来说session即为运行改命令时的session
        '''
        self.session = session
        return isinstance(self.session, WebshellSession) and self.session.server_info.lang in (Webshell.PHP, Webshell.ASP_NET_CS, )

    def run(self, args:Cmdline)-> int:
        args = self.parse.parse_args(args.options)
        ret = self.evalfile('payload', path=args.dest, mode=0o777 if args.mode is None else args.mode, pwd=self.session.pwd)
        ret = ret.data
        if ret is None:
            logger.error(f'Create a directory `{args.dest}` failed')
            return self.STOP
        if ret == '1':
            logger.info(f'Create a directory `{args.dest}` success')
        else:
            logger.error(f'Create a directory `{args.dest}` failed')
            return self.STOP
        return self.SUCCESS
