#!/bin/sh

set -o errexit


version='0.0.1'


shell_quote_and_awk_sanitize() {
	# Sanitize string so it's usable as a shell argument
	
	# Escape single quotes
	escaped=$(echo "$1" | sed "s/'/'\"'\"'/g")

	case "$escaped" in
		'' )
			# Empty string
			return
			;;
		*[![:alnum:]_\./~-]* )
			# Argument is not clean, needs quoting
			escaped="'$escaped'"
			;;
		* )
			# Argument contains only safe characters
			;;
	esac

	# Sanitize further so it's usable as an argument to AWK 'sub' functions
	echo "$escaped" | sed 's/\\/\\\\/g; s/&/\\\\&/g'
}

simplify_home() {
	echo "$1" | awk -v home="$HOME" '{ sub("^"home, "~"); print }'
}


add_short_opt() {
	case "$1" in
		*' '-[[:alnum:]]* )
			printf '%s%s' "$1" "$2"
			;;
		* )
			printf '%s -%s' "$1" "$2"
	esac
}


# Helper function for tools like xzcat, bzcat
# If the path to archive contains slashes (e.g. 'dir/file.xz')
# then force outputting to current directory, as opposed to 'dir/file'
force_output_dir_to_current_dir() {
	if [ -z "$output_dir" ]; then
		case "$archive_path" in
			*/* )
				output_dir='.'
				;;
		esac
	fi
}


get_tools_for_format() {
	case "$1" in
		*.rar ) echo "unrar bsdtar 7z" ;;
		*.tar.lrz )
			# In some cases we invoke 'tar' directly,
			# but lrzuntar depends on 'tar' so we don't specify it
			if [ "$helpar_command" = 'extract' ]; then
				echo "lrzuntar bsdtar" 
			elif [ "$helpar_command" = 'ls' ]; then
				echo "lrzcat bsdtar" 
			fi
			return
			;;
		*.tar | *.tar.* | *.tgz | *.tbz | *.txz | *.tlz | *.tzo )
			echo "tar bsdtar 7z"
			return
			;;
		*.7z )  echo "7z bsdtar" ;;
		*.deb ) echo "dpkg-deb" ;;
		*.arj ) echo "unarj 7z" ;;
		*.lha ) echo "lha bsdtar 7z" ;;
		?*.lzo ) 
			# BUG with bsdtar: 
			# bsdtar tvf test.lzo
			# lzop: <stdin>: warning: this is a multipart archive (try option '-N')
			echo "lzop" ;;
		*.cpio ) 
			echo "cpio bsdtar 7z"
			;;
		*.exe ) echo "7z" ;;
	esac

	case "$helpar_command" in
		extract )
			case "$1" in
				*.zip )   echo "unzip bsdtar 7z" ;;
				?*.bz2 )  echo "bunzip2 7z" ;;
				?*.gz )   echo "gunzip 7z" ;;
				?*.xz )   echo "unxz 7z" ;;
				?*.lzma ) echo "unlzma 7z" ;;
				?*.zst )  echo "unzstd 7z" ;;
				?*.lz4 )  echo "unlz4 7z" ;;
				?*.lrz )  echo "lrunzip" ;;
				?*.lz )   echo "lzip 7z" ;;
				?*.Z )    echo "uncompress 7z" ;;
			esac
			;;
		ls )
			case "$1" in
				*.zip ) echo "zipinfo bsdtar 7z" ;;
				?*.bz | ?*.bz2 | ?*.gz | ?*.xz | ?*.lzma | ?*.zst | ?*.lz4 | ?*.lrz | ?*.lz | ?*.Z )
					echo "echo"
					;;
			esac
			;;
		cat )
			case "$1" in
				*.zip )   echo "unzip bsdtar 7z" ;;
				?*.bz2 )  echo "bzcat 7z" ;;
				?*.gz )   echo "zcat 7z" ;;
				?*.xz )   echo "xzcat 7z" ;;
				?*.lzma ) echo "lzcat 7z" ;;
				?*.zst )  echo "zstdcat 7z" ;;
				?*.lz4 )  echo "lz4cat 7z" ;;
				?*.lrz )  echo "lrzcat" ;;
				?*.lz )   echo "lzip 7z" ;;
				?*.Z )    echo "uncompress 7z" ;;
			esac
			;;
	esac
}


try_tools() {
	for tool in "$@"; do
		if command -v "$tool" > /dev/null; then 
			echo "$tool"
			return
		fi
	done
	>&2 echo "Error: no extraction tool installed"
	exit 1
}


select_tool_for_format() {
	if [ -n "$force_tool" ]; then
		echo "$force_tool"
		return
	fi
	helpar_tools="$(get_tools_for_format "$1")"
	if [ -n "$only_print_tools" ] && [ -z "$helpar_tools" ]; then
		if [ -z "$quiet" ]; then
			>&2 printf 'Error: not familiar with this file format.\n'
		fi
		exit 1
	fi

	if [ -z "$helpar_tools" ]; then
		if [ -z "$quiet" ]; then
			>&2 printf 'Warning: not familiar with this file format.\n'
		fi
		helpar_tools="bsdtar 7z"
	fi
	if [ -z "$only_run_command" ]; then
		>&2 printf 'Possible tools: \033[38;5;12m%s\033[m\n' "$(printf '%s' "$helpar_tools" | sed 's/ /, /g')"
	fi

	helpar_tool="$(try_tools $helpar_tools)"
	if [ -z "$only_run_command" ]; then
		if [ "$helpar_tool" != "$helpar_tools" ]; then
			>&2 printf 'Selected tool: \033[38;5;12m%s\033[m' "$helpar_tool"
			>&2 printf ' (use --tool to change the selection)\n'
		fi
	fi
	echo "$helpar_tool"
}



helpar_extract_help() {
	cat <<-_EOF
	Usage: helpar extract ARCHIVE [options...]
		
	    -c, --command                   Only print an suitable command for extraction, do not execute it
	    -d, --delete                    Delete archive after extraction, useful for single compressed files
	    -f, --force, --force-overwrite  Overwrite existing files
	    -h, --help                      Show this help message
	    -o, --output-directory PATH     Extract files into the PATH directory
	    -p, --password PASSWORD         Enter password for encrypted archives
	    -r, --run                       Only execute the command, do not print it or ask confirmation
	    -q, --quiet                     Don't print extra information
	    -s, --skip, --force-skip        Skip existing files
	    -S, --simulate                  Aliases for --command
	    -t, --tool TOOL                 Force usage of specific TOOL for extraction
	    -T, --tools                     List all known TOOLs for extracting the given file, then exit
	    -X, --extract-to, --to PATH     Aliases for --output-directory
	    -y, --yes                       Print a suitable command and execute it, do not ask confirmation
	_EOF
}

helpar_extract_get_opts() {
	options=ho:X:p:fdqscSryt:T
	longopts=help,to:,output-directory:,extract-to:,password:,force,force-overwrite,delete,quiet,force-skip,skip,command,simulate,run,yes,tool:,tools
	parsed=$(getopt --options=$options --longoptions=$longopts --name "$0" -- "$@")
	eval set -- "$parsed"


	while [ -n "$1" ]; do
		case "$1" in 
			-h | --help )
				helpar_extract_help
				exit 0
				;;
			-r | --run )
				only_run_command=y
				shift
				;;
			-y | --yes )
				skip_confirm=y
				shift
				;;
			-o | --output-directory | -X | --extract-to | --to )
				# Get rid of trailing slash
				output_dir="${2%/}"
				shift 2
				;;
			-p | --password )
				password="$2"
				shift 2
				;;
			-f | --force-overwrite | --force )
				force=y
				shift
				;;
			-s | --force-skip | --skip )
				skip=y
				shift
				;;
			-d | --delete )
				delete=y
				shift
				;;
			-q | --quiet )
				quiet=y
				shift
				;;
			-c | --command | -S | --simulate )
				only_print_command=y
				shift
				;;
			-t | --tool )
				force_tool="$2"
				shift 2
				;;
			-T | --tools )
				only_print_tools=y
				shift
				;;
			-- )
				shift
				while [ -n "$1" ]; do
					if ! [ -e "$1" ]; then
						if [ -n "$output_dir" ]; then
							>&2 printf "Error: %s does not exist." "$1"
							exit 1
						fi
						output_dir="$1"
					elif [ -d "$1" ]; then
						if [ -n "$output_dir" ]; then
							>&2 echo "Error: specified multiple directories"
							exit 1
						fi
						output_dir="$1"
					else
						if [ -n "$archive_path" ]; then
							>&2 echo "Error: helpar only handles one archive at a time."
							exit 1
						fi
						archive_path="$1"
					fi
					shift
				done
				break
				;;
		esac
	done
	
	if [ -z "$archive_path" ]; then
		helpar_extract_help
		exit 1
	fi

	if [ -n "$force" ] && [ -n "$skip" ]; then
		>&2 echo "Error: can't --skip and --force-overwrite at the same time."
		exit 1
	fi
}


helpar_ls_help() {
	cat <<-_EOF
	Usage: helpar ls ARCHIVE [options...]
	    or helpar list ARCHIVE [options...]
		
	    -c, --command   Only print an suitable command for listing, do not execute it
	    -r, --run       Only execute the command, do not print it or ask confirmation
	    -S, --simulate  Aliases for --command
	    -t, --tool TOOL Force usage of specific TOOL for listing
	    -T, --tools     List all known TOOLs suitable for the given archive, then exit
	    -y, --yes       Print a suitable command and execute it, do not ask confirmation
	    -1, --oneline   Print one file name per line, and no other information
	_EOF
}


helpar_ls_get_opts() {
	options=h1cSryt:T
	longopts=help,oneline,command,simulate,run,yes,tool:,tools
	parsed=$(getopt --options=$options --longoptions=$longopts --name "$0" -- "$@")
	eval set -- "$parsed"


	while true; do
		case "$1" in 
			-h | --help )
				helpar_ls_help
				exit 0
				;;
			-r | --run )
				only_run_command=y
				shift
				;;
			-y | --yes )
				skip_confirm=y
				shift
				;;
			-1 | --oneline )
				one_line=y
				shift
				;;
			-c | --command | -S | --simulate )
				only_print_command=y
				shift
				;;
			-t | --tool )
				force_tool="$2"
				shift 2
				;;
			-T | --tools )
				only_print_tools=y
				shift
				;;
			-- )
				shift
				archive_path="$1"
				break
				;;
		esac
	done
	
	if [ -z "$archive_path" ]; then
		helpar_ls_help
		exit 1
	fi
}


make_command() {
	if [ -n "$only_print_tools" ]; then
		only_run_command=y
		run_command="echo $(get_tools_for_format "$archive_path")"
		return
	fi

	tool="$(select_tool_for_format "$archive_path" "extract")"

	case "$tool" in
		unzip )
			handle_delete_manually=y
			archive_path_handle_dash=leading-dot

			run="unzip"

			[ -n "$force" ] && run="$(add_short_opt "$run" o)"
			[ -n "$skip" ] && run="$(add_short_opt "$run" n)"
			[ -n "$quiet" ] && run="$(add_short_opt "$run" q)"
			
			# Handle password which starts with -
			case "$password" in
				'' )
					# No password
					;;
				* )
					run="$run -PPASSWORD"
					;;
			esac

			run="$run ARCHIVE_PATH"
			[ -n "$output_dir" ] && run="$run -d OUTPUT_DIR"
			;;
		zipinfo )
			archive_path_handle_dash=leading-dot

			[ -n "$output_dir" ] && run="$run -d OUTPUT_DIR"

			if [ -n "$one_line" ]; then
				run="zipinfo -1 ARCHIVE_PATH"
			else
				run="zipinfo ARCHIVE_PATH"
			fi
			;;
		unrar )
			archive_path_handle_dash=double-dash

			if [ "$helpar_command" = 'ls' ]; then
				if [ -n "$one_line" ]; then
					run="unrar lb ARCHIVE_PATH"
				else
					run="unrar l ARCHIVE_PATH"
				fi
			elif [ "$helpar_command" = 'extract' ]; then
				handle_delete_manually=y

				run="unrar x"

				[ -n "$force" ] && run="$run -o+"
				[ -n "$skip" ] && run="$run -o-" # Skips files but sometimes exits with an error anyway, sigh...
				[ -n "$quiet" ] && run="$run -idq"
				[ -n "$password" ] && run="$run -pPASSWORD"

				run="$run ARCHIVE_PATH"

				# unrar always treats the last argument as the output dir,
				# but only if it has a trailing slash
				if [ -n "$output_dir" ]; then
					output_dir="$output_dir/"
					run="$run OUTPUT_DIR"
				fi
			fi
			;;
		tar )
			if [ "$helpar_command" = 'ls' ]; then
				archive_path_handle_dash='leading-dot'

				case "$archive_path" in
					*.tar.gz | *.tgz )
						[ -n "$one_line" ] && run="tar tzf" || run="tar tzvf"
						;;
					*.tar.bz | *.tbz )
						[ -n "$one_line" ] && run="tar tjf" || run="tar tjvf"
						;;
					* )
						[ -n "$one_line" ] && run="tar tf" || run="tar tvf"
						;;
				esac
				run="$run ARCHIVE_PATH"
			elif [ "$helpar_command" = 'extract' ]; then
				# We put the -C argument at the end, so we can't use --
				archive_path_handle_dash='leading-dot'

				handle_delete_manually=y
				handle_output='mkdir'

				case "$archive_path" in
					*.tar.gz | *.tgz )
						[ -n "$quiet" ] && run="tar xzf" || run="tar xzvf"
						;;
					*.tar.bz | *.tbz )
						[ -n "$quiet" ] && run="tar xjf" || run="tar xjvf"
						;;
					* )
						[ -n "$quiet" ] && run="tar xf" || run="tar xvf"
						;;
				esac
	 
				run="$run ARCHIVE_PATH"
				[ -n "$skip" ] && run="$run --skip-old-files"
				[ -z "$skip" ] && [ -z "$force" ] && run="$run -k"
				[ -n "$output_dir" ] && run="$run -C OUTPUT_DIR"
			fi
			;;
		lrzuntar )
			# Special case, not handled by GNU tar
			# BUG?: man lrzip says it does not override by default, but lrzuntar does
			# BUG?: lrzuntar can't handle --long options
			# BUG?: can't specify password as arg
			archive_path_handle_dash='double-dash'
			output_dir_handle_dash='leading-dot'
			handle_output='mkdir'

			if [ -n "$force" ]; then
				run="lrzuntar"
				handle_delete_manually=y

				if [ -n "$quiet" ]; then
					# BUG
					echo "Sorry, the --quiet option is not supported by lrzuntar." >&2
					exit 1
				fi
				[ -n "$output_dir" ] && run="$run -O OUTPUT_DIR"
				run="$run ARCHIVE_PATH"
			else
				run="lrzcat"
				[ -n "$delete" ] && run="$run --delete"
				if [ -n "$quiet" ]; then
					run="$run --very-quiet ARCHIVE_PATH | tar x"
				else
					run="$run ARCHIVE_PATH | tar xv"
				fi

				if [ -n "$skip" ]; then
					run="$run --skip-old-files"
				else
					run="$run -k"
				fi
				[ -n "$output_dir" ] && run="$run -C OUTPUT_DIR"
			fi
			;;
		lrzcat )
			# ls only
			archive_path_handle_dash=double-dash
			run="lrzcat --quiet ARCHIVE_PATH"
			if [ -n "$one_line" ]; then
				run="lrzcat --very-quiet ARCHIVE_PATH | tar t"
			else
				run="lrzcat --quiet ARCHIVE_PATH | tar tv"
			fi
			;;
		bsdtar )
			# We put the -C argument at the end, so we can't use --
			archive_path_handle_dash='leading-dot'
			output_dir_handle_dash='leading-dot'
			if [ "$helpar_command" = 'extract' ]; then
				handle_delete_manually=y
				handle_output='mkdir'

				[ -n "$quiet" ] && run="bsdtar xf" || run="bsdtar xvf"
				run="$run ARCHIVE_PATH"
				[ -z "$force" ] && run="$run -k"
				[ -n "$password" ] && run="$run --passphrase PASSWORD"
				[ -n "$output_dir" ] && run="$run -C OUTPUT_DIR"
			elif [ "$helpar_command" = 'ls' ]; then
				[ -n "$one_line" ] && run="bsdtar tf" || run="bsdtar tvf"
				run="$run ARCHIVE_PATH"
			fi
			;;
		dpkg-deb )
			archive_path_handle_dash='double-dash'
			output_dir_handle_dash='double-dash-after-archive-path'
			run="dpkg-deb"
			if [ "$helpar_command" = 'extract' ]; then
				handle_delete_manually=y
				handle_skip_manually=dir
				handle_force=always-skip

				[ -n "$quiet" ] && run="$run --extract" || run="$run --vextract"
				
				if [ -n "$skip" ]; then
					echo "Sorry, the --skip flag is not supported for deb." >&2
					exit 1
				fi
				if [ -z "$output_dir" ]; then
					if [ -z "$force" ]; then
						echo "Sorry, extracting .deb packages to working directory might overwrite files" >&2
						echo "Use --force or change --output-directory" >&2
						exit 1
					fi
					output_dir="."
				fi
				run="$run ARCHIVE_PATH OUTPUT_DIR"
			elif [ "$helpar_command" = 'ls' ]; then
				run="$run --contents ARCHIVE_PATH"
				[ -n "$one_line" ] && run="$run | cut -c51- | tail -n +2"
			fi
			;;
		bunzip2 | gunzip | unxz | unlzma | lzip )
			handle_output='mkdir'
			handle_skip_manually=path

			case "$archive_path" in
				*.bz )
					archive_path_handle_dash='double-dash'
					remove_suffix='.bz'
					run_unzip="bunzip2"
					run_cat="bzcat"
					;;
				*.bz2 )
					archive_path_handle_dash='double-dash'
					remove_suffix='.bz2'
					run_unzip="bunzip2"
					run_cat="bzcat"
					;;
				*.gz )
					archive_path_handle_dash='double-dash'
					remove_suffix='.gz'
					run_unzip="gunzip"
					run_cat="zcat"
					;;
				*.xz )
					archive_path_handle_dash='double-dash'
					remove_suffix='.xz'
					run_unzip="unxz"
					run_cat="xzcat"
					;;
				*.lzma )
					archive_path_handle_dash='double-dash'
					remove_suffix='.lzma'
					run_unzip="unlzma"
					run_cat="lzcat"
					;;
				*.lz )
					archive_path_handle_dash='double-dash'
					remove_suffix='.lz'
					run_unzip="lzip -d"
					run_cat="lzip -d --stdout"
					;;
			esac

			force_output_dir_to_current_dir

			if [ -n "$output_dir" ]; then
				handle_delete_manually=y
				handle_force=noclobber
				run="$run_cat ARCHIVE_PATH > OUTPUT_PATH"
			else
				run="$run_unzip"
				[ -z "$delete" ] && run="$run --keep"
				[ -n "$force" ] && run="$run --force"
				run="$run ARCHIVE_PATH"
			fi
			;;
		unzstd )
			archive_path_handle_dash='double-dash'
			handle_skip_manually=path
			output_dir_no_tilde=y
			handle_output='mkdir'

			remove_suffix='.zst'
			run="unzstd"

			force_output_dir_to_current_dir

			[ -n "$quiet" ] && run="$run --quiet"
			[ -n "$delete" ] && run="$run --rm"
			[ -n "$force" ] && run="$run --force"
			[ -n "$output_dir" ] && run="$run --output-dir-flat=OUTPUT_DIR"

			run="$run ARCHIVE_PATH"
			;;
		unlz4 )
			archive_path_handle_dash='double-dash'
			output_path_handle_dash='double-dash-after-archive-path'
			handle_skip_manually=path
			handle_output='mkdir'

			remove_suffix='.lz4'
			run="unlz4"

			force_output_dir_to_current_dir

			[ -n "$quiet" ] && run="$run --quiet"
			[ -n "$delete" ] && run="$run --rm"
			[ -n "$force" ] && run="$run --force"
			run="$run ARCHIVE_PATH"
			[ -n "$output_dir" ] && run="$run OUTPUT_PATH"
			;;
		lrunzip )
			archive_path_handle_dash='double-dash'
			output_dir_handle_dash='leading-dot'
			handle_skip_manually=path
			handle_output='mkdir'

			remove_suffix='.lrz'
			run="lrunzip"

			[ -n "$quiet" ] && run="$run --very-quiet"
			[ -n "$delete" ] && run="$run --delete"
			[ -n "$force" ] && run="$run --force"

			force_output_dir_to_current_dir
			if [ -n "$output_dir" ]; then
				run="$run --outdir OUTPUT_DIR"
			fi
			run="$run ARCHIVE_PATH"
			;;
		lzop )
			archive_path_handle_dash=double-dash
			output_dir_no_tilde=y
			if [ "$helpar_command" = 'extract' ]; then
				handle_output='mkdir'

				run="lzop -x"

				[ -n "$quiet" ] && run="$run --quiet"
				[ -n "$delete" ] && run="$run --delete"
				[ -n "$force" ] && run="$run --force"
				if [ -n "$skip" ]; then
					echo "Sorry, the --skip flag is not supported for lzop." >&2
					exit 1
				fi

				[ -n "$output_dir" ] && run="$run --path=OUTPUT_DIR"

				run="$run ARCHIVE_PATH"
			elif [ "$helpar_command" = 'ls' ]; then
				must_cd=y
				if [ -n "$one_line" ]; then
					run="lzop --list --quiet -P ARCHIVE_PATH | cut -c40-"
				else
					run="lzop --ls -P ARCHIVE_PATH"
				fi
			fi
			;;
		unarj )
			handle_delete_manually=y
			archive_path_handle_dash='leading-dot'

			if [ -n "$one_line" ] || [ -n "$quiet" ] || [ -n "$force" ] || [ -n "$skip" ] || [ -n "$output_dir" ]; then
				echo "Sorry, unarj does not support any options." >&2
				exit 1
			fi

			if [ "$helpar_command" = 'extract' ]; then
				run="unarj x ARCHIVE_PATH"
			elif [ "$helpar_command" = 'ls' ]; then
				run="unarj l ARCHIVE_PATH"
			fi
			;;
		lha )
			archive_path_handle_dash=leading-dot
			if [ "$helpar_command" = 'extract' ]; then
				handle_delete_manually=y
				output_dir_no_tilde=y
				run="lha x"

				# Free lhasa does not support short opts
				[ -n "$quiet" ] && run="${run}q"
				[ -n "$force" ] && run="${run}f"
				if [ -n "$skip" ]; then
					echo "Sorry, the --skip flag is not supported for lha." >&2
					exit 1
				fi
				[ -n "$output_dir" ] && run="${run}w=OUTPUT_DIR"

				# The non-free lha supports --
				run="$run ARCHIVE_PATH"
			elif [ "$helpar_command" = 'ls' ]; then
				# The non-free lha supports --
				if [ -n "$one_line" ]; then
					# this might be a better way to handle this,
					# but only supported in non-free lha
					#run="lha l -vq ARCHIVE_PATH | sed '0~2d'"
					run="lha -lq ARCHIVE_PATH | cut -c52-"
				else
					run="lha -l ARCHIVE_PATH"
				fi
			fi
			;;
		cpio )
			# BUG?: GNU cpio creates output directory automatically, but writes nothing and crashes
			if [ "$helpar_command" = 'extract' ]; then
				handle_delete_manually=y
				[ -n "$delete" ] && archive_path_handle_dash="leading-dot"
				output_dir_no_tilde=y

				run="cpio -i"

				[ -n "$quiet" ] && run="$run -d --quiet" || run="$run -vd"
				[ -n "$force" ] && run="$run --unconditional"
				[ -n "$output_dir" ] && run="$run --directory=OUTPUT_DIR"
				
				run="$run < ARCHIVE_PATH"
			elif [ "$helpar_command" = 'ls' ]; then
				if [ -n "$one_line" ]; then
					run="cpio -t --quiet < ARCHIVE_PATH"
				else
					run="cpio -t -v < ARCHIVE_PATH"
				fi
			fi
			;;
		uncompress )
			archive_path_handle_dash='leading-dot'
			handle_skip_manually=path
			handle_output='mkdir'

			remove_suffix='.Z'
			run="uncompress"

			force_output_dir_to_current_dir

			# Let's be strictly POSIX-compliant in the case of .Z
			if [ -z "$delete" ] || [ -n "$output_dir" ]; then
				handle_delete_manually=y
				handle_force=noclobber
				run="uncompress -c ARCHIVE_PATH > OUTPUT_PATH"
			elif [ -n "$force" ]; then
				run="uncompress -f ARCHIVE_PATH"
			else
				run="uncompress ARCHIVE_PATH"
			fi
			;;
		7z )
			archive_path_handle_dash='double-dash'
			output_dir_no_tilde=y
			if [ "$helpar_command" = 'extract' ]; then
				handle_delete_manually=y

				run="7z x"

				[ -n "$force" ] && run="$run -aoa"
				[ -n "$skip" ] && run="$run -aos"
				[ -n "$output_dir" ] && run="$run -oOUTPUT_DIR"
				[ -n "$password" ] && run="$run -pPASSWORD"
				[ -n "$quiet" ] && run="$run -bd"

				run="$run ARCHIVE_PATH"
			elif [ "$helpar_command" = 'ls' ]; then
				if [ -n "$one_line" ]; then
					run="7z l -slt -ba ARCHIVE_PATH | grep '^Path = ' | cut -d' ' -f3-"
				else
					run="7z l ARCHIVE_PATH"
				fi
			fi
			;;
		echo )
			if [ -n "$one_line" ]; then
				run='filename=ARCHIVE_PATH; filename="${filename%.*}"; echo "${filename##*/}"'
			else
				only_run_command=y
				run="echo 'ARCHIVE_PATH is just a single compressed file.'"
			fi
	esac


	#
	# Handling parameters for 'extract' command
	# 
	
	if [ "$handle_force" = 'always-skip' ] && [ -z "$force" ]; then
		skip=y
	fi

	# Manually check if file exists
	if [ -n "$handle_skip_manually" ] && [ -n "$skip" ]; then
		case "$handle_skip_manually" in
			path )
				output_path_handle_dash='leading-dot'
				check_path="OUTPUT_PATH"
				;;
			dir )
				output_dir_handle_dash='leading-dot'
				check_path="OUTPUT_DIR"
				;;
		esac
		# We still have to --delete even if we manually skip.
		# handle_delete_manually is handled later.
		if [ -n "$delete" ] && [ -z "$handle_delete_manually" ]; then
			run="([ -e $check_path ] && rm ARCHIVE_PATH) || $run"
		else
			run="[ -e $check_path ] || $run"
		fi
		used_or=y
	fi

	# Manually remove archive on successful extraction
	if [ -n "$handle_delete_manually" ] && [ -n "$delete" ]; then
		if [ -n "$used_or" ]; then
			run="($run) && rm ARCHIVE_PATH"
		else
			run="$run && rm ARCHIVE_PATH"
		fi
	fi

	# 'set -o noclobber' to prevent overwriting files by default
	if [ "$handle_force" = 'noclobber' ] && [ -z "$force" ] && [ -z "$skip" ]; then
		run="$(printf 'set -o noclobber\n%s' "$run")"
	fi

	# Manually create output directory
	if [ "$handle_output" = 'mkdir' ] && [ -n "$output_dir" ]; then
		output_dir_handle_dash='leading-dot'
		run="$(printf 'mkdir -p OUTPUT_DIR\n%s' "$run")"
	fi

	archive_dir="$(dirname -- "$archive_path")"
	if [ -n "$must_cd" ]; then
		archive_path="$(basename -- "$archive_path")"
		case "$archive_dir" in
			. )
				# Archive dir is current dir
				;;
			-* )
				# Handle dir starting with -
				run="$(printf 'cd -- ARCHIVE_DIR\n%s\ncd -' "$run" )"
				;;
			* )
				run="$(printf 'cd ARCHIVE_DIR\n%s\ncd -' "$run" )"
				;;
		esac
	fi

	#
	# Handling common parameters
	# 

	archive_path_arg="$(shell_quote_and_awk_sanitize "$archive_path")"
	output_dir_arg="$(shell_quote_and_awk_sanitize "$output_dir")"
	password_arg="$(shell_quote_and_awk_sanitize "$password")"
	archive_dir_arg="$(shell_quote_and_awk_sanitize "$archive_dir")"

	base_name_no_ext="$(basename -- "$archive_path" "$remove_suffix")"
	case "$output_dir" in
		'' )
			output_path="$base_name_no_ext"
			;;
		./* )
			# Special handling for force_output_dir_to_current_dir
			# Won't need the leading ./ after this point
			output_path="${output_path##./}"
			;;
		*/ )
			output_path="$output_dir$base_name_no_ext"
			;;
		* )
			output_path="$output_dir/$base_name_no_ext"
			;;
	esac

	output_path_arg="$(shell_quote_and_awk_sanitize "$output_path")"

	case "$archive_path_handle_dash" in
		'double-dash' )
			case "$archive_path_arg" in
				-* | \'-* )
					archive_path_prefix="-- "
					;;
			esac
			;;
		'leading-dot' )
			case "$archive_path_arg" in
				-* )
					archive_path_arg="./$archive_path_arg"
					;;
				\'-* )
					archive_path_arg="'./${archive_path_arg##\'}"
					;;
			esac
			;;
	esac

	case "$output_path_handle_dash" in
		'double-dash' )
			case "$output_path_arg" in
				-* | \'-* )
					output_path_prefix="-- "
					;;
			esac
			;;
		'leading-dot' )
			case "$output_path_arg" in
				-* )
					output_path_arg="./$output_path_arg"
					;;
				\'-* )
					output_path_arg="'./${output_path_arg##\'}"
					;;
			esac
			;;
	esac

	case "$output_dir_handle_dash" in
		'double-dash' )
			case "$output_dir_arg" in
				-* | \'-* )
					output_dir_prefix="-- "
					;;
			esac
			;;
		'double-dash-after-archive-path' )
			case "$archive_path_prefix" in
				--* )
					# already used -- prefix
					;;
				* )
					case "$output_dir_arg" in
						-* | \'-* )
							output_dir_prefix="-- "
							;;
					esac
			esac
			;;
		'leading-dot' )
			case "$output_dir_arg" in
				-* )
					output_dir_arg="./$output_dir_arg"
					;;
				\'-* )
					output_dir_arg="'./${output_dir_arg##\'}"
					;;
			esac
			;;
	esac


	archive_path_display="$(simplify_home "$archive_path_arg")"
	if [ "$output_dir_no_tilde" = y ]; then
		output_dir_display="$output_dir_arg"
	else
		output_dir_display="$(simplify_home "$output_dir_arg")"
	fi
	output_path_display="$(simplify_home "$output_path_arg")"
	archive_dir_display="$(simplify_home "$archive_dir_arg")"

	awk_program='{
		gsub("ARCHIVE_PATH", archive_path);
		gsub("ARCHIVE_DIR", archive_dir);
		gsub("OUTPUT_PATH", output_path);
		gsub("OUTPUT_DIR", output_dir);
		gsub("PASSWORD", password);
		print;
	}'

	# Pretty string starts as bright blue, then reset at the end
	# Arguments in pretty string are green, then the following text is bright blue
	# Password in pretty string is red

	pretty_command="$(printf "\033[38;5;12m%s\033[m" "$run" | awk \
		-v archive_path="$archive_path_prefix\033[38;5;2m$archive_path_display\033[38;5;12m" \
		-v archive_dir="\033[38;5;2m$archive_dir_display\033[38;5;12m" \
		-v output_path="$output_path_prefix\033[38;5;2m$output_path_display\033[38;5;12m" \
		-v output_dir="$output_dir_prefix\033[38;5;2m$output_dir_display\033[38;5;12m" \
		-v password="\033[38;5;1m\"\$PASSWORD\"\033[38;5;12m" \
		"$awk_program")"


	run_command="$(printf '%s' "$run" | awk \
		-v archive_path="$archive_path_prefix$archive_path_arg" \
		-v archive_dir="$archive_dir_arg" \
		-v output_path="$output_path_prefix$output_path_arg" \
		-v output_dir="$output_dir_prefix$output_dir_arg" \
		-v password="$password_arg" \
		"$awk_program")"
}




do_command() {
	if [ -n "$only_print_command" ]; then
		printf '%s\n' "$run_command"
	elif [ -n "$only_run_command" ]; then
		( eval "$run_command" )
	elif [ -n "$skip_confirm" ]; then
		>&2 printf '%s\n' "$pretty_command"
		( eval "$run_command" )
	else
		>&2 printf '%s\n\nRun this command? [Y(yes)|n(no)] ' "$pretty_command"
		read -r response
		case "$response" in
			n|N|no|No|nO|NO )
				;;
			* )
				( eval "$run_command" )
				;;
		esac
	fi
}


helpar_print_usage() {
	cat <<-_EOF
	Available commands:
	    c, cat        (WIP) Print out a single file from an archive
	    e, x, extract Extract files from an archive, or decompress a compressed file
	    l, ls, list   List files in an archive, and other information
	_EOF
}

helpar_print_version() {
	echo "$version"
}

helpar_help_generic() {
	echo "Usage: helpar COMMAND..."
	echo "   or  helpar --help COMMAND..."
	echo "   or  helpar --version"
	echo
	helpar_print_usage			
}

while true; do
	case "$1" in
		e|x|extract )
			shift
			helpar_command="extract"
			if [ -n "$helpar_help" ]; then
				helpar_extract_help
			else
				helpar_extract_get_opts "$@"
				make_command
				do_command
			fi
			break
			;;
		l|ls|list )
			shift
			helpar_command="ls"
			if [ -n "$helpar_help" ]; then
				helpar_ls_help
			else
				helpar_ls_get_opts "$@"
				make_command
				do_command
			fi
			break
			;;
		-h|--help )
			helpar_help=y
			shift
			;;
		-v|--version )
			helpar_print_version
			exit 0
			;;
		-* )
			echo "Unknown option: $1"
			helpar_help_generic
			exit 1
			;;
		"" )
			helpar_help_generic
			if [ -n "$helpar_help" ] || [ -n "$helpar_version" ]; then
				exit 0
			else
				exit 1
			fi
			;;
		* )
			echo "Unknown command: $1"
			helpar_print_usage
			exit 1
			;;
	esac
done
