/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */

/*
 *  Engrampa
 *
 *  Copyright (C) 2004, 2008 Free Software Foundation, Inc.
 *
 *  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 2 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, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include <stdio.h>
#include <config.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <libgen.h>

#include <glib.h>
#include <glib/gi18n.h>
#include <zip.h>

#include "file-data.h"
#include "file-utils.h"
#include "fr-process.h"
#include "glib-utils.h"
#include "fr-command.h"
#include "fr-command-7z.h"
#include "rar-utils.h"
#include "fr-error.h"
#include "gtk-utils.h"

static void fr_command_7z_class_init  (FrCommand7zClass *class);
static void fr_command_7z_init        (FrCommand        *afile);
static void fr_command_7z_finalize    (GObject          *object);
static void fr_command_7z_test          (FrCommand   *comm);
static void fr_command_7z_begin_command (FrCommand *comm);
static void add_password_arg           (FrCommand  *comm,
                                        const char *password,
                                        gboolean    always_specify);

static gboolean spd_support = FALSE;
static gboolean unexpected_end_of_archive = FALSE;
static gboolean password_required = FALSE;
static gboolean password_handled = FALSE;

/* Parent Class */

static FrCommandClass *parent_class = NULL;


/* -- list -- */


static time_t
mktime_from_string (char *date_s,
		    char *time_s)
{
	struct tm   tm = {0, };
	char      **fields;

	tm.tm_isdst = -1;

	/* date */

	fields = g_strsplit (date_s, "-", 3);
	if (fields[0] != NULL) {
		tm.tm_year = atoi (fields[0]) - 1900;
		tm.tm_mon = atoi (fields[1]) - 1;
		tm.tm_mday = atoi (fields[2]);
	}
	g_strfreev (fields);

	/* time */

	fields = g_strsplit (time_s, ":", 3);
	if (fields[0] != NULL) {
		tm.tm_hour = atoi (fields[0]);
		if (fields[1] != NULL) {
			tm.tm_min = atoi (fields[1]);
			if (fields[2] != NULL)
				tm.tm_sec = atoi (fields[2]);
		}
	}
	g_strfreev (fields);

	return mktime (&tm);
}


static void
list__process_line (char     *line,
		    gpointer  data)
{
	FrCommand    *comm = FR_COMMAND (data);
	FrCommand7z  *p7z_comm = FR_COMMAND_7Z (comm);
	char        **fields;
	FileData     *fdata;

	g_return_if_fail (line != NULL);

	if (! p7z_comm->list_started) {
		if (strncmp (line, "p7zip Version ", 14) == 0) {
			const char *ver_start;
			int         ver_len;
			char        version[256];

			ver_start = eat_spaces (line + 14);
			ver_len = strchr (ver_start, ' ') - ver_start;
			strncpy (version, ver_start, ver_len);
			version[ver_len] = 0;

			if ((strcmp (version, "4.55") < 0) && (ver_len > 1) && (version[1] == '.'))
				p7z_comm->old_style = TRUE;
			else
				p7z_comm->old_style = FALSE;
			if ((strcmp (version, "9.38") < 0) && (ver_len > 1) && (version[1] == '.'))
				spd_support = FALSE;
			else
				spd_support = TRUE;
		}
		else if (p7z_comm->old_style && (strncmp (line, "Listing archive: ", 17) == 0))
			p7z_comm->list_started = TRUE;
		else if (! p7z_comm->old_style && (strcmp (line, "----------") == 0))
			p7z_comm->list_started = TRUE;
		else if (strncmp (line, "Multivolume = ", 14) == 0) {
			fields = g_strsplit (line, " = ", 2);
			comm->multi_volume = (strcmp (fields[1], "+") == 0);
			g_strfreev (fields);
		}
		else if (strncmp (line, "Unexpected end of archive", 25) == 0)  {
			unexpected_end_of_archive = TRUE;
		}
		return;
	}

	if (strcmp (line, "") == 0) {
		if (p7z_comm->fdata != NULL) {
			if (p7z_comm->fdata->original_path == NULL) {
				file_data_free (p7z_comm->fdata);
				p7z_comm->fdata = NULL;
			}
			else {
				fdata = p7z_comm->fdata;
				if (fdata->dir)
					fdata->name = dir_name_from_path (fdata->full_path);
				else
					fdata->name = g_strdup (file_name_from_path (fdata->full_path));
				fdata->path = remove_level_from_path (fdata->full_path);
				fr_command_add_file (comm, fdata);
				p7z_comm->fdata = NULL;
			}
		}
		return;
	}

	if (p7z_comm->fdata == NULL)
		p7z_comm->fdata = file_data_new ();

	fields = g_strsplit (line, " = ", 2);

	if (g_strv_length (fields) < 2) {
		g_strfreev (fields);
		return;
	}

	fdata = p7z_comm->fdata;

	if (strcmp (fields[0], "Path") == 0) {
		fdata->free_original_path = TRUE;
		gchar *converted = get_converted_utf8_string(fields[1]);
		if (converted != NULL) {
			fdata->original_path = converted;
		} else {
			fdata->original_path = g_strdup (fields[1]);
		}
		fdata->full_path = g_strconcat ((fdata->original_path[0] != '/') ? "/" : "",
						fdata->original_path,
						(fdata->dir && (fdata->original_path[strlen (fdata->original_path) - 1] != '/')) ? "/" : "",
						NULL);
	}
	else if (strcmp (fields[0], "Folder") == 0) {
		fdata->dir = (strcmp (fields[1], "+") == 0);
		if (fdata->dir && fdata->original_path != NULL) {
			gsize path_len = strlen(fdata->original_path);
			if (path_len > 0 && fdata->original_path[path_len - 1] != '/') {
				char *old_path = fdata->original_path;
				fdata->original_path = g_strconcat(old_path, "/", NULL);
				if (fdata->free_original_path) {
					g_free(old_path);
				}
				fdata->free_original_path = TRUE;

				gsize len = strlen(fdata->full_path);
				if (len > 0 && fdata->full_path[len - 1] != '/') {
					char *new_full_path = g_strconcat(fdata->full_path, "/", NULL);
					g_free(fdata->full_path);
					fdata->full_path = new_full_path;
				}

			}
		}
	}
	else if (strcmp (fields[0], "Size") == 0) {
		fdata->size = g_ascii_strtoull (fields[1], NULL, 10);
	}
	else if (strcmp (fields[0], "Modified") == 0) {
		char **modified_fields;

		modified_fields = g_strsplit (fields[1], " ", 2);
		if (modified_fields[0] != NULL)
			fdata->modified = mktime_from_string (modified_fields[0], modified_fields[1]);
		g_strfreev (modified_fields);
	}
	else if (strcmp (fields[0], "Encrypted") == 0) {
		if (strcmp (fields[1], "+") == 0)
			fdata->encrypted = TRUE;
	}
	else if (strcmp (fields[0], "Method") == 0) {
		if (strstr (fields[1], "AES") != NULL)
			fdata->encrypted = TRUE;

		/* 检测是否使用了 ZSTD 压缩算法。
		 * 如果是，标记 compression 为 FR_COMPRESSION_ZSTD_ZIP。
		 * 这一步是为了在后续解压时识别出 ZSTD 压缩包，因为 punzip 不支持 ZSTD。
		 */
		if (strstr (fields[1], "ZSTD") != NULL || strstr (fields[1], "zstd") != NULL)
			comm->compression = FR_COMPRESSION_ZSTD_ZIP;
	}
	else if (strcmp (fields[0], "Attributes") == 0) {
		if (fields[1][0] == 'D') {
			fdata->dir = TRUE;
			if (fdata->original_path != NULL) {
				gsize path_len = strlen(fdata->original_path);
				if (path_len > 0 && fdata->original_path[path_len - 1] != '/') {
					char *old_path = fdata->original_path;
					fdata->original_path = g_strconcat(old_path, "/", NULL);
					if (fdata->free_original_path) {
						g_free(old_path);
					}
					fdata->free_original_path = TRUE;

					gsize len = strlen(fdata->full_path);
					if (len > 0 && fdata->full_path[len - 1] != '/') {
						char *new_full_path = g_strconcat(fdata->full_path, "/", NULL);
						g_free(fdata->full_path);
						fdata->full_path = new_full_path;
					}
				}
			}
		}
	}
	g_strfreev (fields);
}


static void
fr_command_7z_begin_command (FrCommand *comm)
{
	if (is_mime_type (comm->mime_type, "application/zip") && is_program_in_path ("7za-zstd"))
		fr_process_begin_command (comm->process, "7za-zstd");
	else if (is_program_in_path ("7za"))
		fr_process_begin_command (comm->process, "7za");
	else if (is_program_in_path ("7z"))
		fr_process_begin_command (comm->process, "7z");
	else if (is_program_in_path ("7zr"))
		fr_process_begin_command (comm->process, "7zr");
}


static void
add_password_arg (FrCommand     *comm,
		  const char    *password,
		  gboolean       always_specify)
{
	if (always_specify || ((password != NULL) && (*password != 0))) {
		char *arg;

		arg = g_strconcat ("-p", password, NULL);
		fr_process_add_arg (comm->process, arg);
		g_free (arg);
		password_handled = TRUE;
	}
}


static void
list__begin (gpointer data)
{
	FrCommand7z *p7z_comm = data;

	if (p7z_comm->fdata != NULL) {
		file_data_free (p7z_comm->fdata);
		p7z_comm->fdata = NULL;
	}
	p7z_comm->list_started = FALSE;
}


/* -- tar.7z 列表支持 -- */

/* 检测文件是否为 tar.7z 格式（通过文件名后缀） */
static gboolean
is_tar_7z_by_suffix (const char *filename)
{
	if (filename == NULL)
		return FALSE;

	/* 检查文件名后缀 */
	gboolean result = g_str_has_suffix (filename, ".tar.7z") ||
	                  g_str_has_suffix (filename, ".TAR.7Z") ||
	                  g_str_has_suffix (filename, ".tar.7Z") ||
	                  g_str_has_suffix (filename, ".TAR.7z");

	return result;
}

/* 解析 tar -tvf 输出的日期格式 */
#define TAR_DATE_FORMAT "%Y-%m-%d %H:%M"

static time_t
tar_mktime_from_string (const char *time_s)
{
	struct tm tm = {0, };
	tm.tm_isdst = -1;
	strptime (time_s, TAR_DATE_FORMAT, &tm);
	return mktime (&tm);
}

/* 获取 tar 输出行中的最后一个字段（文件名） */
static char*
tar_7z_get_last_field (const char *line,
                       int         start_from,
                       int         field_n)
{
	const char *f_start, *f_end;

	line = line + start_from;

	f_start = line;
	while ((*f_start == ' ') && (*f_start != *line))
		f_start++;
	f_end = f_start;

	while ((field_n > 0) && (*f_end != 0)) {
		if (*f_end == ' ') {
			field_n--;
			if (field_n == 1)
				f_start = f_end;
		}
		f_end++;
	}

	if (*f_start == ' ')
		f_start++;

	return g_strdup (f_start);
}

/* 解析 tar -tvf 的输出行 */
static void
process_line__tar_list (char     *line,
                        gpointer  data)
{
	FileData    *fdata;
	FrCommand   *comm = FR_COMMAND (data);
	char       **fields;
	int          date_idx;
	char        *field_date, *field_size, *field_name;
	char        *name;

	g_return_if_fail (line != NULL);

	/* tar -tvf 输出格式：
	 * -rw-r--r-- user/group  12345 2024-01-01 12:00 path/to/file
	 * 查找日期模式 YYYY-MM-DD HH:MM */
	date_idx = file_list__get_index_from_pattern (line, "%n%n%n%n-%n%n-%n%n %n%n:%n%n");
	if (date_idx < 0)
		return;

	fdata = file_data_new ();

	/* 获取文件大小 */
	field_size = file_list__get_prev_field (line, date_idx, 1);
	fdata->size = g_ascii_strtoull (field_size, NULL, 10);
	g_free (field_size);

	/* 获取修改时间 */
	field_date = g_strndup (line + date_idx, 16);
	fdata->modified = tar_mktime_from_string (field_date);
	g_free (field_date);

	/* 获取文件路径 */
	field_name = tar_7z_get_last_field (line, date_idx, 3);
	fields = g_strsplit (field_name, " -> ", 2);

	if (fields[1] == NULL) {
		g_strfreev (fields);
		fields = g_strsplit (field_name, " link to ", 2);
	}

	name = g_strcompress (fields[0]);
	if (*name == '/') {
		fdata->full_path = g_strdup (name);
		fdata->original_path = fdata->full_path;
	} else {
		fdata->full_path = g_strconcat ("/", name, NULL);
		fdata->original_path = fdata->full_path + 1;
	}
	g_free (name);

	/* 尝试转换文件名编码 */
	name = g_filename_from_utf8 (fdata->original_path, -1, NULL, NULL, NULL);
	if (name)
		fdata->original_path = name;

	/* 处理符号链接 */
	if (fields[1] != NULL)
		fdata->link = g_strdup (fields[1]);
	g_strfreev (fields);
	g_free (field_name);

	/* 判断是否为目录 */
	fdata->dir = line[0] == 'd';
	if (fdata->dir)
		fdata->name = dir_name_from_path (fdata->full_path);
	else
		fdata->name = g_strdup (file_name_from_path (fdata->full_path));
	fdata->path = remove_level_from_path (fdata->full_path);

	/* 添加到文件列表 */
	if (*fdata->name == 0)
		file_data_free (fdata);
	else
		fr_command_add_file (comm, fdata);
}

/* tar.7z 格式的列表函数 */
static void
fr_command_7z_list_tar_7z (FrCommand *comm)
{
	char *temp_dir;
	char *base_name;
	char *tar_name;
	char *tar_path;

	g_print ("[DEBUG] fr_command_7z_list_tar_7z: start, filename=%s\n", comm->filename);

	/* 1. 创建临时目录 */
	temp_dir = get_temp_work_dir (NULL);
	if (temp_dir == NULL) {
		g_warning ("fr_command_7z_list_tar_7z: failed to create temp dir");
		return;
	}
	g_print ("[DEBUG] fr_command_7z_list_tar_7z: temp_dir=%s\n", temp_dir);

	/* 2. 构建 tar 文件名（去掉 .7z 后缀）
	 * 例如：test.tar.7z -> test.tar */
	base_name = g_path_get_basename (comm->filename);
	tar_name = g_strndup (base_name, strlen (base_name) - 3);  /* 去掉 ".7z" */
	tar_path = g_build_filename (temp_dir, tar_name, NULL);
	g_print ("[DEBUG] fr_command_7z_list_tar_7z: tar_filename=%s\n", tar_path);

	/* 3. 用 7z 解压到临时目录 */
	fr_command_7z_begin_command (comm);
	fr_process_add_arg (comm->process, "e");
	fr_process_add_arg (comm->process, "-bd");
	fr_process_add_arg (comm->process, "-y");
	fr_process_add_arg_concat (comm->process, "-o", temp_dir, NULL);
	add_password_arg (comm, comm->password, FALSE);
	fr_process_add_arg (comm->process, "--");
	fr_process_add_arg (comm->process, comm->filename);
	fr_process_end_command (comm->process);
	g_print ("[DEBUG] fr_command_7z_list_tar_7z: queued 7z extract command\n");

	/* 4. 用 tar -tvf 列出内容 */
	fr_process_begin_command (comm->process, "tar");
	fr_process_set_out_line_func (comm->process, process_line__tar_list, comm);
	fr_process_add_arg (comm->process, "--force-local");
	fr_process_add_arg (comm->process, "--no-wildcards");
	fr_process_add_arg (comm->process, "-tvf");
	fr_process_add_arg (comm->process, tar_path);
	fr_process_end_command (comm->process);
	g_print ("[DEBUG] fr_command_7z_list_tar_7z: queued tar list command\n");

	/* 5. 清理临时 tar 文件 */
	fr_process_begin_command (comm->process, "rm");
	fr_process_add_arg (comm->process, "-f");
	fr_process_add_arg (comm->process, tar_path);
	fr_process_end_command (comm->process);
	g_print ("[DEBUG] fr_command_7z_list_tar_7z: queued rm tar file\n");

	/* 6. 清理临时目录 */
	fr_process_begin_command (comm->process, "rm");
	fr_process_add_arg (comm->process, "-rf");
	fr_process_add_arg (comm->process, temp_dir);
	fr_process_end_command (comm->process);
	g_print ("[DEBUG] fr_command_7z_list_tar_7z: queued rm temp dir\n");

	/* 7. 启动进程 */
	fr_process_start (comm->process);

	/* 清理 */
	g_free (temp_dir);
	g_free (base_name);
	g_free (tar_name);
	g_free (tar_path);
}


static void
fr_command_7z_list (FrCommand  *comm)
{
	/* 初始化压缩类型为普通模式。
	 * 在列出文件列表的过程中，如果发现 ZSTD 压缩的文件，会更新此状态。
	 */
	comm->compression = FR_COMPRESSION_NORMAL;

	rar_check_multi_volume (comm);

	/* 检测是否为 tar.7z 格式
	 * 优先通过文件名后缀判断，也检查 MIME type */
	gboolean is_tar_7z = is_tar_7z_by_suffix (comm->filename);
	if (!is_tar_7z && comm->mime_type != NULL) {
		is_tar_7z = is_mime_type (comm->mime_type, "application/x-7z-compressed-tar");
	}

				FileData *fdata = file_data_new ();

	if (is_tar_7z) {
		/* tar.7z 格式：先解压 7z，再列出 tar 内容 */
		fr_command_7z_list_tar_7z (comm);
		return;
	}

	/* 7z 后端只处理 UTF-8 ZIP，设置默认编码 */
	/* if (is_mime_type(comm->mime_type, "application/zip")) {
		if (comm->filename_encoding == NULL) {
			comm->filename_encoding = g_strdup("UTF-8");
			comm->encoding_source = FR_ENCODING_SOURCE_DEFAULT;
		}
	}
*/

	fr_process_set_out_line_func (comm->process, list__process_line, comm);

	fr_command_7z_begin_command (comm);
	fr_process_set_begin_func (comm->process, list__begin, comm);
	fr_process_add_arg (comm->process, "l");
	fr_process_add_arg (comm->process, "-slt");
	fr_process_add_arg (comm->process, "-bd");
	fr_process_add_arg (comm->process, "-y");
	add_password_arg (comm, comm->password, FALSE);
	fr_process_add_arg (comm->process, "--");
	fr_process_add_arg (comm->process, comm->filename);
	fr_process_end_command (comm->process);

	fr_process_start (comm->process);
}


static void
parse_progress_line (FrCommand  *comm,
		     const char *prefix,
		     const char *message_prefix,
		     const char *line)
{
	int prefix_len;

	prefix_len = strlen (prefix);
	if (strncmp (line, prefix, prefix_len) == 0)
		fr_command_progress (comm, (double) ++comm->n_file / (comm->n_files + 1));
}


static void
process_line__add (char     *line,
		   gpointer  data)
{
	FrCommand *comm = FR_COMMAND (data);

	if (strstr (line, "Enter password") != NULL)
		password_required = TRUE;

	if ((comm->volume_size > 0) && (strncmp (line, "Creating archive", 16) == 0)) {
		char  *volume_filename;
		GFile *volume_file;

		volume_filename = g_strconcat (comm->filename, ".001", NULL);
		volume_file = g_file_new_for_path (volume_filename);
		fr_command_set_multi_volume (comm, volume_file);

		g_object_unref (volume_file);
		g_free (volume_filename);
	}

	if (comm->n_files != 0)
		parse_progress_line (comm, "Compressing  ", _("Adding file: "), line);
}


static void
fr_command_7z_add (FrCommand     *comm,
		   const char    *from_file,
		   GList         *file_list,
		   const char    *base_dir,
		   gboolean       update,
		   gboolean       recursive)
{
	GList *scan;

	fr_process_use_standard_locale (comm->process, TRUE);
	fr_process_set_out_line_func (comm->process,
				      process_line__add,
				      comm);

	if (is_mime_type (comm->mime_type, "application/zip")
	    && is_program_in_path("pzip")
	    && ((comm->password == NULL) || !(*comm->password != 0) )
	    && !(comm->volume_size > 0)
	    && !update
	    && comm->creating_archive
	    && (comm->compression != NULL && comm->compression != FR_COMPRESSION_COPY_ONLY && comm->compression != FR_COMPRESSION_ZSTD_ZIP)
	) {
		fr_process_begin_command (comm->process, "pzip");

		if (base_dir != NULL)
			fr_process_set_working_dir (comm->process, base_dir);

		/* preserve links. */
		fr_process_add_arg (comm->process, "-y");

		fr_process_add_arg (comm->process, "--concurrency");
		fr_process_add_arg (comm->process, "32");

		fr_process_add_arg (comm->process, "--level");
		fr_process_add_arg (comm->process, "1");


		fr_process_add_arg (comm->process, comm->filename);
		fr_process_add_arg (comm->process, "--");

		char * parent_dir_name = g_path_get_dirname(g_path_get_dirname(comm->filename));

		GList * tmp_file_list = g_list_reverse(g_list_copy(file_list));
		char * tmp_file_basename = NULL;
		char * first_file = NULL;
		for (scan = tmp_file_list; scan; scan = scan->next) {
			if (NULL == tmp_file_basename) {
				tmp_file_basename = g_strdup(scan->data);
				fr_process_add_arg (comm->process, scan->data);

			}
			else if (!g_str_has_prefix(scan->data, tmp_file_basename)){
				tmp_file_basename = g_strdup(scan->data);
				fr_process_add_arg (comm->process, scan->data);
			}
		}

		fr_process_end_command (comm->process);
	}
	else {
		gboolean is_use_zstd =  FALSE;
		if (comm->compression == FR_COMPRESSION_ZSTD_ZIP) {
			is_use_zstd = TRUE;
		}

		if (is_use_zstd) {
			fr_process_begin_command (comm->process, "7za-zstd");
		}
		else {
			fr_command_7z_begin_command (comm);
		}

		if (update)
			fr_process_add_arg (comm->process, "u");
		else
			fr_process_add_arg (comm->process, "a");

		if (base_dir != NULL) {
			fr_process_set_working_dir (comm->process, base_dir);
		}

		if (is_mime_type (comm->mime_type, "application/zip")
			|| is_mime_type (comm->mime_type, "application/x-cbz"))
		{
			fr_process_add_arg (comm->process, "-tzip");
			if (comm->password != NULL && *comm->password != 0) {
				fr_process_add_arg (comm->process, "-mem=AES256");
			}
		}
		if (is_use_zstd) {
			fr_process_add_arg (comm->process, "-m0=zstd");
		}
		if (spd_support) fr_process_add_arg (comm->process, "-spd");
		fr_process_add_arg (comm->process, "-bd");
		fr_process_add_arg (comm->process, "-y");
		add_password_arg (comm, comm->password, FALSE);
		if ((comm->password != NULL)
			&& (*comm->password != 0)
			&& comm->encrypt_header
			&& fr_command_is_capable_of (comm, FR_COMMAND_CAN_ENCRYPT_HEADER))
		{
			fr_process_add_arg (comm->process, "-mhe=on");
		}

		/* fr_process_add_arg (comm->process, "-ms=off"); FIXME: solid mode off? */

		switch (comm->compression) {
			case FR_COMPRESSION_COPY_ONLY: {
				fr_process_add_arg (comm->process, "-mx=0");
				break;
			}
			default: {
				fr_process_add_arg (comm->process, "-mx=1");
				break;
			}
		}

		if (is_mime_type (comm->mime_type, "application/x-ms-dos-executable"))
			fr_process_add_arg (comm->process, "-sfx");

		if (comm->volume_size > 0)
			fr_process_add_arg_printf (comm->process, "-v%ub", comm->volume_size);

		if (from_file != NULL)
			fr_process_add_arg_concat (comm->process, "-i@", from_file, NULL);

		if (from_file == NULL)
			for (scan = file_list; scan; scan = scan->next)
				/* Files prefixed with '@' need to be handled specially */
				if (g_str_has_prefix (scan->data, "@"))
					fr_process_add_arg_concat (comm->process, "-i!", scan->data, NULL);

		fr_process_add_arg (comm->process, "--");
		fr_process_add_arg (comm->process, comm->filename);

		if (from_file == NULL)
			for (scan = file_list; scan; scan = scan->next)
				/* Skip files prefixed with '@', already added */
				if (!g_str_has_prefix (scan->data, "@")){
					fr_process_add_arg (comm->process, scan->data);
				}

		fr_process_end_command (comm->process);
	}
}

static void
process_line__delete (char     *line,
		      gpointer  data)
{
	FrCommand *comm = FR_COMMAND (data);

	if ((strstr (line, "Wrong password") != NULL)
	    || (strstr (line, "Enter password") != NULL))
	{
		password_required = TRUE;
	}
}

static void
fr_command_7z_delete (FrCommand  *comm,
		      const char *from_file,
		      GList      *file_list)
{
	GList *scan;

	fr_process_set_out_line_func (comm->process,
				      process_line__delete,
				      comm);

	fr_command_7z_begin_command (comm);
	fr_process_add_arg (comm->process, "d");
	if (spd_support) fr_process_add_arg (comm->process, "-spd");
	fr_process_add_arg (comm->process, "-bd");
	fr_process_add_arg (comm->process, "-y");
	if (is_mime_type (comm->mime_type, "application/x-ms-dos-executable"))
		fr_process_add_arg (comm->process, "-sfx");

	if (from_file != NULL)
		fr_process_add_arg_concat (comm->process, "-i@", from_file, NULL);

	if (from_file == NULL)
		for (scan = file_list; scan; scan = scan->next)
			/* Files prefixed with '@' need to be handled specially */
			if (g_str_has_prefix (scan->data, "@"))
				fr_process_add_arg_concat (comm->process, "-i!", scan->data, NULL);

	add_password_arg (comm, FR_COMMAND (comm)->password, FALSE);

	fr_process_add_arg (comm->process, "--");
	fr_process_add_arg (comm->process, comm->filename);

	if (from_file == NULL)
		for (scan = file_list; scan; scan = scan->next)
			/* Skip files prefixed with '@', already added */
			if (!g_str_has_prefix (scan->data, "@"))
				fr_process_add_arg (comm->process, scan->data);

	fr_process_end_command (comm->process);
}


static void
process_line__extract (char     *line,
		       gpointer  data)
{
	FrCommand *comm = FR_COMMAND (data);

	if (comm->n_files != 0)
		parse_progress_line (comm, "Extracting  ", _("Extracting file: "), line);

	if ((strstr (line, "Wrong password") != NULL)
	    || (strstr (line, "Enter password") != NULL))
	{
		password_required = TRUE;
	}
}

#define ZIP_SPECIAL_CHARACTERS       "[]*?!^-\\"

static void
process_line__punzip (char     *line,
		      gpointer  data)
{
	FrCommand  *comm = FR_COMMAND (data);

	if (line == NULL)
		return;

	if (comm->n_files != 0) {
		double fraction = (double) ++comm->n_file / (comm->n_files + 1);
		fr_command_progress (comm, fraction);
	}
	else
		fr_command_message (comm, line);
}

static void
fr_command_7z_extract_punzip (FrCommand  *comm,
			      const char *from_file,
			      GList      *file_list,
			      const char *dest_dir,
			      gboolean    overwrite,
			      gboolean    skip_older,
			      gboolean    junk_paths)
{
	GList *scan;

	fr_process_set_out_line_func (comm->process,
				      process_line__punzip,
				      comm);

	fr_process_begin_command (comm->process, "punzip");

	if (dest_dir != NULL) {
		fr_process_add_arg (comm->process, "-d");
		fr_process_add_arg (comm->process, dest_dir);
	}

	/* punzip 专用参数 */
	/* 静默模式（可选，根据需要启用） */
	fr_process_add_arg (comm->process, "-q");

	/* 并发数（可选，使用默认值，或根据需要设置） */
	/* fr_process_add_arg (comm->process, "--concurrency");
	fr_process_add_arg (comm->process, "8"); */

	/* 处理文件列表：使用 -i 参数指定要解压的文件 */
	if (file_list != NULL) {
		for (scan = file_list; scan; scan = scan->next) {
			char *escaped;
			escaped = escape_str (scan->data, ZIP_SPECIAL_CHARACTERS);
			fr_process_add_arg (comm->process, "-i");
			fr_process_add_arg (comm->process, escaped);
			g_free (escaped);
		}
	}

	/* punzip 不需要 -- 分隔符，直接跟文件名 */
	fr_process_add_arg (comm->process, comm->filename);

	fr_process_end_command (comm->process);
}

static gboolean
check_use_punzip (FrCommand *comm, GList *file_list)
{
	if (!is_mime_type (comm->mime_type, "application/zip"))
		return FALSE;

	if (!is_program_in_path ("punzip"))
		return FALSE;

	if (is_encry_zip_file(comm->filename)) {
		return FALSE;
	}

	gboolean large_file_found = FALSE;
	guint i;

	if (file_list == NULL) {
		for (i = 0; i < comm->files->len; i++) {
			FileData *fd = g_ptr_array_index (comm->files, i);
			if (fd->size > 500 * 1024 * 1024) {
				large_file_found = TRUE;
				break;
			}
		}
	}
	else {
		for (i = 0; i < comm->files->len; i++) {
			FileData *fd = g_ptr_array_index (comm->files, i);
			if (fd->size > 500 * 1024 * 1024) {
				GList *scan;
				for (scan = file_list; scan; scan = scan->next) {
					if (strcmp (scan->data, fd->full_path) == 0 ||
					    strcmp (scan->data, fd->original_path) == 0)
					{
						large_file_found = TRUE;
						break;
					}
				}
			}
			if (large_file_found) break;
		}
	}

	return large_file_found;
}

// 优化判断压缩包是否为tar.7z的逻辑
gboolean get_is_tar_7z (FrCommand  *comm,
		        const char *from_file,
		        GList      *file_list)
{
	gboolean is_tar_7z = FALSE;
	debug(DEBUG_INFO, "get_is_tar_7z  start\n");

	/* 方法1：通过文件名后缀判断 */
	if (is_tar_7z_by_suffix (comm->filename)) {
		is_tar_7z = TRUE;
	}

	/* 方法2：通过 MIME type 判断 */
	if (!is_tar_7z && comm->mime_type != NULL) {
		if (is_mime_type (comm->mime_type, "application/x-7z-compressed-tar")) {
			is_tar_7z = TRUE;
		}
	}

	g_print ("[DEBUG] get_is_tar_7z: filename=%s, mime_type=%s, result=%s\n",
	         comm->filename ? comm->filename : "NULL",
	         comm->mime_type ? comm->mime_type : "NULL",
	         is_tar_7z ? "TRUE" : "FALSE");

	return is_tar_7z;
}

/* 辅助函数：添加 tar 解压命令到进程队列 */
static void
add_tar_extract_command (FrCommand  *comm,
                         const char *tar_path,
                         const char *dest_dir,
                         gboolean    overwrite,
                         gboolean    skip_older,
                         GList      *file_list)
{
	GList *scan;

	fr_process_begin_command (comm->process, "tar");
	fr_process_add_arg (comm->process, "--force-local");
	fr_process_add_arg (comm->process, "--no-wildcards");
	fr_process_add_arg (comm->process, "--no-unquote");
	fr_process_add_arg (comm->process, "-p");

	if (overwrite)
		fr_process_add_arg (comm->process, "--overwrite");
	else
		fr_process_add_arg (comm->process, "-k");
	if (skip_older)
		fr_process_add_arg (comm->process, "--keep-newer-files");

	fr_process_add_arg (comm->process, "-xf");
	fr_process_add_arg (comm->process, tar_path);

	if (dest_dir != NULL) {
		fr_process_add_arg (comm->process, "-C");
		fr_process_add_arg (comm->process, dest_dir);
	}

	fr_process_add_arg (comm->process, "--");

	/* 添加要提取的文件列表（如果指定） */
	if (file_list != NULL) {
		for (scan = file_list; scan; scan = scan->next) {
			if (!g_str_has_prefix (scan->data, "@"))
				fr_process_add_arg (comm->process, scan->data);
		}
	}

	fr_process_end_command (comm->process);
}

/* 辅助函数：添加 rm 清理命令到进程队列 */
static void
add_rm_command (FrCommand *comm, const char *path, gboolean recursive)
{
	fr_process_begin_command (comm->process, "rm");
	if (recursive)
		fr_process_add_arg (comm->process, "-rf");
	else
		fr_process_add_arg (comm->process, "-f");
	fr_process_add_arg (comm->process, path);
	fr_process_end_command (comm->process);
}

static void
fr_command_7z_extract (FrCommand  *comm,
		       const char *from_file,
		       GList      *file_list,
		       const char *dest_dir,
		       gboolean    overwrite,
		       gboolean    skip_older,
		       gboolean    junk_paths)
{
	fr_process_set_out_line_func (comm->process,
				      process_line__extract,
				      comm);
	fr_process_set_err_line_func (comm->process,
				      process_line__extract,
				      comm);

	// 优化判断压缩包是否为tar.7z的逻辑，需在解压前判断
	gboolean is_tar_7z = get_is_tar_7z(comm, from_file, file_list);

	/*
	 * 检查是否可以使用 punzip 进行快速解压。
	 * 注意：punzip 不支持 ZSTD 压缩算法。
	 * 因此，如果检测到压缩包包含 ZSTD 压缩的文件 (comm->compression == FR_COMPRESSION_ZSTD_ZIP)，
	 * 必须跳过 punzip 优化，回退到使用标准的 7z/7za-zstd 解压流程。
	 * 标准流程会自动调用 fr_command_7z_begin_command，那里会正确选择 7za-zstd。
	 */
	if (!is_tar_7z && check_use_punzip (comm, file_list) && comm->compression != FR_COMPRESSION_ZSTD_ZIP) {
		fr_command_7z_extract_punzip (comm, from_file, file_list, dest_dir, overwrite, skip_older, junk_paths);
		return;
	}

	/* tar.7z 格式需要特殊处理：先解压到临时目录，再从 tar 中提取文件 */
	if (is_tar_7z) {
		char *temp_dir;
		char *base_name;
		char *tar_name;
		char *tar_path;

		/* 1. 创建临时目录 */
		temp_dir = get_temp_work_dir (NULL);
		if (temp_dir == NULL) {
			g_warning ("fr_command_7z_extract: failed to create temp dir for tar.7z");
			return;
		}

		base_name = g_path_get_basename (comm->filename);
		tar_name = g_strndup (base_name, strlen (base_name) - 3);  /* 去掉 ".7z" */
		tar_path = g_build_filename (temp_dir, tar_name, NULL);

		g_print ("[DEBUG] fr_command_7z_extract: tar.7z mode, temp_dir=%s, tar_path=%s\n", temp_dir, tar_path);

		/* 2. 用 7z 解压 .tar 到临时目录 */
		fr_process_use_standard_locale (comm->process, TRUE);
		fr_command_7z_begin_command (comm);
		fr_process_add_arg (comm->process, "e");
		fr_process_add_arg (comm->process, "-bd");
		fr_process_add_arg (comm->process, "-y");
		add_password_arg (comm, comm->password, FALSE);
		fr_process_add_arg_concat (comm->process, "-o", temp_dir, NULL);
		fr_process_add_arg (comm->process, "--");
		fr_process_add_arg (comm->process, comm->filename);
		fr_process_end_command (comm->process);

		/* 3. 从 tar 中提取指定文件到目标目录 */
		add_tar_extract_command (comm, tar_path, dest_dir, overwrite, skip_older, file_list);

		/* 4. 清理临时文件和目录 */
		add_rm_command (comm, tar_path, FALSE);
		add_rm_command (comm, temp_dir, TRUE);

		g_free (temp_dir);
		g_free (base_name);
		g_free (tar_name);
		g_free (tar_path);
		return;
	}

	// 处理普通 .7z 文件
	fr_process_use_standard_locale (comm->process, TRUE);

	fr_command_7z_begin_command (comm);

	if (junk_paths)
		fr_process_add_arg (comm->process, "e");
	else
		fr_process_add_arg (comm->process, "x");

	if (spd_support) fr_process_add_arg (comm->process, "-spd");
	fr_process_add_arg (comm->process, "-bd");
	fr_process_add_arg (comm->process, "-y");
	add_password_arg (comm, comm->password, FALSE);

	if (dest_dir != NULL)
		fr_process_add_arg_concat (comm->process, "-o", dest_dir, NULL);

	if (from_file != NULL)
		fr_process_add_arg_concat (comm->process, "-i@", from_file, NULL);

	GList *scan;
	if (from_file == NULL)
		for (scan = file_list; scan; scan = scan->next)
			/* Files prefixed with '@' need to be handled specially */
			if (g_str_has_prefix (scan->data, "@"))
				fr_process_add_arg_concat (comm->process, "-i!", scan->data, NULL);

	fr_process_add_arg (comm->process, "--");
	fr_process_add_arg (comm->process, comm->filename);

	if (from_file == NULL)
		for (scan = file_list; scan; scan = scan->next)
			/* Skip files prefixed with '@', already added */
			if (!g_str_has_prefix (scan->data, "@"))
				fr_process_add_arg (comm->process, scan->data);

	if (unexpected_end_of_archive) fr_process_set_ignore_error (comm->process, TRUE);

	fr_process_end_command (comm->process);
}

static void
fr_command_7z_extract_from_archive (FrCommand  *comm,
		       const char *from_file,
		       GList      *file_list,
		       const char *dest_dir,
		       gboolean    overwrite,
		       gboolean    skip_older,
		       gboolean    junk_paths)
{
	// 优化判断压缩包是否为tar.7z的逻辑，需在解压前判断
	gboolean is_tar_7z = get_is_tar_7z(comm, from_file, file_list);

	if (!is_tar_7z && check_use_punzip (comm, file_list) && comm->compression != FR_COMPRESSION_ZSTD_ZIP) {
		fr_command_7z_extract_punzip (comm, from_file, file_list, dest_dir, overwrite, skip_older, junk_paths);
		return;
	}

	/* tar.7z 格式需要特殊处理：先解压到临时目录，再从 tar 中提取文件 */
	if (is_tar_7z) {
		char *temp_dir;
		char *base_name;
		char *tar_name;
		char *tar_path;

		/* 1. 创建临时目录 */
		temp_dir = get_temp_work_dir (NULL);
		if (temp_dir == NULL) {
			g_warning ("fr_command_7z_extract_from_archive: failed to create temp dir for tar.7z");
			return;
		}

		base_name = g_path_get_basename (comm->filename);
		tar_name = g_strndup (base_name, strlen (base_name) - 3);  /* 去掉 ".7z" */
		tar_path = g_build_filename (temp_dir, tar_name, NULL);

		g_print ("[DEBUG] fr_command_7z_extract_from_archive: tar.7z mode, temp_dir=%s, tar_path=%s\n", temp_dir, tar_path);

		/* 2. 用 7z 解压 .tar 到临时目录 */
		fr_process_use_standard_locale (comm->process, TRUE);
		fr_command_7z_begin_command (comm);
		fr_process_add_arg (comm->process, "e");
		fr_process_add_arg (comm->process, "-bd");
		fr_process_add_arg (comm->process, "-y");
		add_password_arg (comm, comm->password, FALSE);
		fr_process_add_arg_concat (comm->process, "-o", temp_dir, NULL);
		fr_process_add_arg (comm->process, "--");
		fr_process_add_arg (comm->process, comm->filename);
		fr_process_end_command (comm->process);

		/* 3. 从 tar 中提取指定文件到目标目录 */
		add_tar_extract_command (comm, tar_path, dest_dir, overwrite, skip_older,
		                         (from_file == NULL) ? file_list : NULL);

		/* 4. 清理临时文件和目录 */
		add_rm_command (comm, tar_path, FALSE);
		add_rm_command (comm, temp_dir, TRUE);

		g_free (temp_dir);
		g_free (base_name);
		g_free (tar_name);
		g_free (tar_path);
		return;
	}

	// 处理普通 .7z 文件
	fr_process_use_standard_locale (comm->process, TRUE);
	fr_process_set_out_line_func (comm->process,
				      process_line__extract,
				      comm);
	fr_command_7z_begin_command (comm);

	if (junk_paths)
		fr_process_add_arg (comm->process, "e");
	else
		fr_process_add_arg (comm->process, "x");

	if (spd_support) fr_process_add_arg (comm->process, "-spd");
	fr_process_add_arg (comm->process, "-bd");
	fr_process_add_arg (comm->process, "-y");
	add_password_arg (comm, comm->password, FALSE);

	if (dest_dir != NULL)
		fr_process_add_arg_concat (comm->process, "-o", dest_dir, NULL);

	if (from_file != NULL)
		fr_process_add_arg_concat (comm->process, "-i@", from_file, NULL);

	GList *scan;
	if (from_file == NULL)
		for (scan = file_list; scan; scan = scan->next)
			/* Files prefixed with '@' need to be handled specially */
			if (g_str_has_prefix (scan->data, "@"))
				fr_process_add_arg_concat (comm->process, "-i!", scan->data, NULL);

	fr_process_add_arg (comm->process, "--");
	fr_process_add_arg (comm->process, comm->filename);

	if (from_file == NULL)
		for (scan = file_list; scan; scan = scan->next)
			/* Skip files prefixed with '@', already added */
			if (!g_str_has_prefix (scan->data, "@"))
				fr_process_add_arg (comm->process, scan->data);

	if (unexpected_end_of_archive) fr_process_set_ignore_error (comm->process, TRUE);

	fr_process_end_command (comm->process);
}


static void
fr_command_7z_test (FrCommand   *comm)
{
	fr_command_7z_begin_command (comm);
	fr_process_add_arg (comm->process, "t");
	fr_process_add_arg (comm->process, "-bd");
	fr_process_add_arg (comm->process, "-y");
	add_password_arg (comm, comm->password, FALSE);
	fr_process_add_arg (comm->process, "--");
	fr_process_add_arg (comm->process, comm->filename);
	fr_process_end_command (comm->process);
}


static void
fr_command_7z_handle_error (FrCommand   *comm,
			    FrProcError *error)
{
	if (error->type == FR_PROC_ERROR_NONE) {
		FileData *first;
		char     *basename;
		char     *testname;

		/* This is a way to fix bug #582712. */

		if (comm->files->len != 1)
			return;

		if (! g_str_has_suffix (comm->filename, ".001"))
			return;

		first = g_ptr_array_index (comm->files, 0);
		basename = g_path_get_basename (comm->filename);
		testname = g_strconcat (first->original_path, ".001", NULL);

		if (strcmp (basename, testname) == 0)
			error->type = FR_PROC_ERROR_ASK_PASSWORD;

		g_free (testname);
		g_free (basename);

		return;
	}

	if ((error->status <= 1) || (unexpected_end_of_archive)) {
		error->type = FR_PROC_ERROR_NONE;
	}
	else {
		if (password_required && ((!password_handled) || (comm->password == NULL) || (comm->password[0] == '\0')))
		{
			error->type = FR_PROC_ERROR_ASK_PASSWORD;
			return;
		}

		/* 如果password_required未设置，但仍怀疑是密码错误，添加额外的检查 */
		if (password_required && comm->password != NULL) {
			error->type = FR_PROC_ERROR_ASK_PASSWORD;
			return;
		}

		GList *scan;

		for (scan = comm->process->out.raw; scan; scan = scan->next) {
			char *line = scan->data;

			if ((strstr (line, "Wrong password") != NULL)
			    || (strstr (line, "Enter password") != NULL))
			{
				error->type = FR_PROC_ERROR_ASK_PASSWORD;
				break;
			}

			if ((strstr (line, "Can not open the file as [7z] archive") != NULL))
			{
				error->type = FR_PROC_ERROR_GENERIC;
				error->gerror = g_error_new (FR_ERROR, error->status, _("Corrupted files or missing volumes"));
				break;
			}
		}

		for (scan = comm->process->err.raw; scan; scan = scan->next) {
			char *line = scan->data;
			g_print("%s\n", line);

			if ((strstr (line, "Wrong password") != NULL)
			    || (strstr (line, "Enter password") != NULL))
			{
				error->type = FR_PROC_ERROR_ASK_PASSWORD;
				break;
			}
			if ((strstr (line, "No more files") != NULL))
			{
				error->type = FR_PROC_ERROR_GENERIC;
				error->gerror = g_error_new (FR_ERROR, error->status, _("Corrupted files or missing volumes"));
				break;
			}
		}
	}
}


const char *sevenz_mime_types[] = { "application/x-7z-compressed",
				    "application/x-arj",
				    "application/vnd.ms-cab-compressed",
				    /*"application/x-cd-image", */
				    /*"application/x-cbr",*/
				    "application/x-cbz",
				    "application/x-ms-dos-executable",
				    "application/x-ms-wim",
				    "application/x-rar",
				    "application/zip", /* zip always at the end and the number of */
				    NULL };            /* place in fr_command_7z_get_mime_types   */


static const char **
fr_command_7z_get_mime_types (FrCommand *comm)
{
	GSettings *settings;
	settings = g_settings_new ("org.mate.engrampa.general");

	if (g_settings_get_boolean (settings, "unar-open-zip") &&
	    is_program_in_path ("unar") && is_program_in_path ("lsar"))
		sevenz_mime_types [8] = NULL;
	else
		g_settings_set_boolean (settings, "unar-open-zip", FALSE);

	g_object_unref (settings);

	return sevenz_mime_types;
}


static FrCommandCap
fr_command_7z_get_capabilities (FrCommand  *comm,
				const char *mime_type,
				gboolean    check_command)
{
	FrCommandCap capabilities;

	capabilities = FR_COMMAND_CAN_ARCHIVE_MANY_FILES;
	if (! is_program_available ("7za", check_command) && ! is_program_available ("7zr", check_command) && ! is_program_available ("7z", check_command))
		return capabilities;

	if (is_mime_type (mime_type, "application/x-7z-compressed")) {
		capabilities |= FR_COMMAND_CAN_READ_WRITE | FR_COMMAND_CAN_CREATE_VOLUMES;
		if (is_program_available ("7z", check_command))
			capabilities |= FR_COMMAND_CAN_ENCRYPT | FR_COMMAND_CAN_ENCRYPT_HEADER;

		if (is_program_available ("7za", check_command)) {
			capabilities |= FR_COMMAND_CAN_COPY_ONLY;
			capabilities |= FR_COMMAND_CAN_ZSTD;
		}
	}
	else if (is_mime_type (mime_type, "application/x-7z-compressed-tar")) {
		capabilities |= FR_COMMAND_CAN_READ_WRITE;
		if (is_program_available ("7z", check_command))
			capabilities |= FR_COMMAND_CAN_ENCRYPT | FR_COMMAND_CAN_ENCRYPT_HEADER;
	}
	else if (is_program_available ("7z", check_command)) {
		if (is_mime_type (mime_type, "application/x-rar")
		    || is_mime_type (mime_type, "application/x-cbr"))
		{
			if (! check_command || g_file_test ("/usr/lib/p7zip/Codecs/Rar29.so", G_FILE_TEST_EXISTS) || g_file_test ("/usr/lib/p7zip/Codecs/Rar.so", G_FILE_TEST_EXISTS)
			    || g_file_test ("/usr/libexec/p7zip/Codecs/Rar29.so", G_FILE_TEST_EXISTS) || g_file_test ("/usr/libexec/p7zip/Codecs/Rar.so", G_FILE_TEST_EXISTS))
				capabilities |= FR_COMMAND_CAN_READ;
		}
		else
			capabilities |= FR_COMMAND_CAN_READ;

		if (is_mime_type (mime_type, "application/x-cbz")
		    || is_mime_type (mime_type, "application/x-ms-dos-executable")
		    || is_mime_type (mime_type, "application/zip"))
		{
			capabilities |= FR_COMMAND_CAN_WRITE | FR_COMMAND_CAN_ENCRYPT;
			if(is_mime_type (mime_type, "application/zip"))
				capabilities |= FR_COMMAND_CAN_ZSTD;
		}
	}
	else if (is_program_available ("7za", check_command)) {
		if (is_mime_type (mime_type, "application/vnd.ms-cab-compressed")
		    || is_mime_type (mime_type, "application/zip"))
		{
			capabilities |= FR_COMMAND_CAN_READ;
		}

		if (is_mime_type (mime_type, "application/zip")){
			capabilities |= FR_COMMAND_CAN_WRITE;
			capabilities |= FR_COMMAND_CAN_ZSTD;
		}
	}

	/* multi-volumes are read-only */
	if ((comm->files->len > 0) && comm->multi_volume && (capabilities & FR_COMMAND_CAN_WRITE))
		capabilities ^= FR_COMMAND_CAN_WRITE;

	return capabilities;
}


static const char *
fr_command_7z_get_packages (FrCommand  *comm,
			    const char *mime_type)
{
	if (is_mime_type (mime_type, "application/x-rar"))
		return PACKAGES ("p7zip,p7zip-rar");
	else if (is_mime_type (mime_type, "application/zip") || is_mime_type (mime_type, "application/vnd.ms-cab-compressed"))
		return PACKAGES ("p7zip,p7zip-full");
	else
		return PACKAGES ("p7zip");
}


static void
fr_command_7z_class_init (FrCommand7zClass *class)
{
	GObjectClass   *gobject_class = G_OBJECT_CLASS (class);
	FrCommandClass *afc;

	parent_class = g_type_class_peek_parent (class);
	afc = (FrCommandClass*) class;

	gobject_class->finalize = fr_command_7z_finalize;

	afc->list             = fr_command_7z_list;
	afc->add              = fr_command_7z_add;
	afc->delete           = fr_command_7z_delete;
	afc->extract          = fr_command_7z_extract;
	afc->extract_from_archive = fr_command_7z_extract_from_archive;
	afc->test             = fr_command_7z_test;
	afc->handle_error     = fr_command_7z_handle_error;
	afc->get_mime_types   = fr_command_7z_get_mime_types;
	afc->get_capabilities = fr_command_7z_get_capabilities;
	afc->get_packages     = fr_command_7z_get_packages;
}


static void
fr_command_7z_init (FrCommand *comm)
{
	comm->propAddCanUpdate             = TRUE;
	comm->propAddCanReplace            = TRUE;
	comm->propAddCanStoreFolders       = TRUE;
	comm->propExtractCanAvoidOverwrite = FALSE;
	comm->propExtractCanSkipOlder      = FALSE;
	comm->propExtractCanJunkPaths      = TRUE;
	comm->propPassword                 = TRUE;
	comm->propTest                     = TRUE;
	comm->propListFromFile             = TRUE;
}


static void
fr_command_7z_finalize (GObject *object)
{
	g_return_if_fail (object != NULL);
	g_return_if_fail (FR_IS_COMMAND_7Z (object));

	/* Chain up */
	if (G_OBJECT_CLASS (parent_class)->finalize)
		G_OBJECT_CLASS (parent_class)->finalize (object);
}


GType
fr_command_7z_get_type ()
{
	static GType type = 0;

	if (! type) {
		GTypeInfo type_info = {
			sizeof (FrCommand7zClass),
			NULL,
			NULL,
			(GClassInitFunc) fr_command_7z_class_init,
			NULL,
			NULL,
			sizeof (FrCommand7z),
			0,
			(GInstanceInitFunc) fr_command_7z_init,
			NULL
		};

		type = g_type_register_static (FR_TYPE_COMMAND,
					       "FRCommand7z",
					       &type_info,
					       0);
	}

	return type;
}
