#!/bin/sh -


export LANG=en_US.UTF-8
readonly _command="${0##*/}"
_dpkg_path="$(apt-config dump | grep 'State::status')"
_dpkg_path="${_dpkg_path#*\"}"
_dpkg_path="${_dpkg_path%\/status*}"
_pwd="$(pwd)"
if [ -z "${_pwd}" ]; then
	_pwd='/'
fi
if ! which sw_vers 2>>/dev/null 1>>/dev/null; then
	_s_path="${HOME}"
else
	_s_path='/var/mobile'
fi

_print_help(){
	echo "Usage: ${_command} [OPTIONS...] <file/folder/package>
	-h			Print this help
	-b	<file/folder>	Build an archive
	-e	<file/folder>	Extract control info
	-x	<file/folder>	Extract files
	-r	<file/folder>	Extract control info and files
	-p	<package>	Repack installed packages to deb (experimental)
	-i	<file>		Print info for archive

	--forced-install	<file>		Force installation for deb files (experimental)
	--forced-uninstall	<package>	Force uninstall from installed (experimental)
Example:
	${_command} -b /tmp/test /tmp/test.deb
	${_command} -b /tmp/test
	${_command} [-e/-x/-r] /tmp/test.deb /tmp/test
	${_command} [-e/-x/-r] /tmp/test.deb
	${_command} --skip-check-exists [-e/-x/-r/-p] <file/folder/package>
	${_command} -p com.nan.test /tmp/com.nan.test.deb
	${_command} -p com.nan.test
	${_command} -i /tmp/test.deb
	${_command} -i /tmp/test.deb Depends"
}

_randnum(){
	if [ -z "${2}" ]; then
		tr -dc 'A-Za-z0-9' < /dev/urandom | head -c "${1}"
	else
		tr -dc "${1}" < /dev/urandom | head -c "${2}"
	fi
}

_check(){
	if [ -z "${1}" ]; then
		echo "${_command}: Invalid"
		exit 1
	fi
	if [ ! -e "${1}" ]; then
		echo "${_command}: Error: No found \"${1}\""
		exit 1
	fi
	if test -f "${1}"; then
		if ! dpkg-deb -I "${1}" 1>>/dev/null 2>>/dev/null; then
			_type='file'
		else
			_type='deb'
		fi
	elif test -d "${1}"; then
		_type='folder'
	else
		_type='unknown'
	fi
}

_test(){
	if test -e "${1}"; then
		if test -f "${1}"; then
			echo 'file'
		elif test -d "${1}"; then
			echo 'folder'
		else
			echo 'notfound'
		fi
	else
		echo 'notfound'
	fi
}

_f_dcrm(){
	if [ -f "${1}" ]; then
		if [ "$(stat --format=%a "${1}")" = '0' ]; then
			chmod -R 0755 "${1}"
		fi
	fi
}

_check_exists(){
	if [ "${_check_exists}" = '1' ]; then
		if test -d "${1}"; then
			echo "${1}_$(_randnum '10')"
		else
			echo "${1}"
		fi
	else
		echo "${1}"
	fi
}

_strip(){
	_file="${1}"
	_file="${_file%\.deb*}"
	echo "${_file}"
	unset _file
}


if [ "${#}" = '0' ]; then
	_print_help
	exit 1
else
	case "${1}" in
		-h|--help)
			_print_help
			exit 0
		;;
		-i|--info)
			_check "${2}"
			if [ ! "${_type}" = 'deb' ]; then
				echo "${_command}: Error: not support type"
				echo "${_command}: type: ${_type}"
				exit 1
			fi
			if [ -z "${3}" ]; then
				_info="$(dpkg-deb -I "${2}")"
				echo "Package: ${_info#*Package: }" | sed 's#^\ ##g' | sed 's#\r$##'
			else
				dpkg-deb -f "${2}" "${3}"
			fi
			exit 0
		;;
	esac
fi
if ! id -u | grep -q '^0$'; then
	exec sudo "${0}" "$@"
fi
if [ "${2}" = '--skip-check-exists' ]; then
	_check_exists='0'
	shift
else
	_check_exists='1'
fi
case "${1}" in
	-e|--control|-x|--extract|-r|--release)
		_check "${2}"
		case "${_type}" in
			deb)
				if [ -n "${3}" ]; then
					_use_folder="$(_check_exists "$(_strip "${3}")")"
				else
					_use_folder="$(_check_exists "$(_strip "${2}")")"
				fi
				if ! mkdir -p "${_use_folder}"; then
					echo "${_command}: Error: Can't mkdir folder"
					exit 1
				fi
				chown -R $(id -u):$(id -g) "${_use_folder}"
				case "${1}" in
					-e|--control)
						dpkg-deb -e "${2}" "${_use_folder}"
						;;
					-x|--extract)
						dpkg-deb -x "${2}" "${_use_folder}"
						;;
					-r|--release)
						dpkg-deb -x "${2}" "${_use_folder}" &
						mkdir -p "${_use_folder}/DEBIAN/"
						dpkg-deb -e "${2}" "${_use_folder}/DEBIAN/"
						wait
						;;
				esac
				echo "${_use_folder}"
				;;
			folder)
				i='1'
				_list="/tmp/$(_randnum '20').tmp"
				find "${2}" -maxdepth 1 -type f -iname '*.deb' | sed 's#.deb$##g' | sort -k2n >"${_list}"
				i_max="$(cat "${_list}" | wc -l)"
				while [ "${i}" -le "${i_max}" ]; do
					_deb_n="$(cat "${_list}" | sed -n "${i}p")"
					echo "${i}: $(deb "${1}" "${_deb_n}.deb")"
					unset _deb_n
					i="$((i+1))"
				done
				rm -rf "${_list}"
				unset _deb_n _list
				;;
			file)
				echo "${_command}: Error: This file is not recognized"
				exit 1
				;;
			unknown)
				echo "${_command}: Error: UnKnown type, not support"
				exit 1
				;;
		esac
			;;
	-b|--build)
		case "${2}" in
			xz)
				_z='xz'
				;;
			gzip)
				_z='gzip'
				;;
			zstd)
				_z='zstd'
				;;
			*)
				_skip_shift='1'
				;;
		esac
		if [ ! "${_skip_shift}" = '1' ]; then
			shift
			_Z='1'
		fi
		if [ -z "${2}" ]; then
			echo "${_command}: Error: null"
			exit 1
		fi
		if [ ! -e "${2}" ]; then
			echo "${_command}: Error: not found"
			exit 1
		fi
		if [ "$(find ${2} -maxdepth 1 -type d -iname 'DEBIAN' | wc -l)" = '1' ]; then
			if [ -n "${3}" ]; then
				if test -f "${3%.deb*}.deb"; then
					_export="${3%.deb*}_$(_randnum '10').deb"
				else
					_export="${3%.deb*}.deb"
				fi
			else
				_export="$(echo "${2}/" | sed 's#//$##g' | sed 's#/$##g')"
				if [ -f "${2}/DEBIAN/control" ]; then
					_export="${_export%/*}"
					_package="$(cat "${2}/DEBIAN/control" | grep '^Package: ' | sed 's#\r$##')"
					_package="${_package#*:\ }"
					_package_version="$(cat "${2}/DEBIAN/control" | grep '^Version: ' | sed 's#\r$##')"
					_package_version="${_package_version#*:\ }"
					_package_architecture="$(cat "${2}/DEBIAN/control" | grep '^Architecture: ' | sed 's#\r$##')"
					_package_architecture="${_package_architecture#*:\ }"
					_export="${_export}/${_package}_${_package_version}_${_package_architecture}"
					if test -f "${_export}.deb"; then
						_export="${_export}_$(_randnum '10').deb"
					else
						_export="${_export}.deb"
					fi
				else
					if test -f "${2}.deb"; then
						_export="${2}_$(_randnum '10').deb"
					else
						_export="${2}.deb"
					fi
				fi
			fi
			_f_dcrm "${2}/DEBIAN/preinst" &
			_f_dcrm "${2}/DEBIAN/postinst" &
			_f_dcrm "${2}/DEBIAN/prerm" &
			_f_dcrm "${2}/DEBIAN/postrm" &
			if [ -f "${2}/DEBIAN/triggers" ]; then
				chmod -R 0644 "${2}/DEBIAN/triggers" 2>>/dev/null 1>>/dev/null &
			fi
			wait
			if [ "${_Z}" = '1' ]; then
				if dpkg-deb -Z "${_z}" -b "${2}" "${_export}" 1>>/dev/null; then
					echo "${_export}"
				else
					echo "${_command}: Error: Build deb Failure"
					exit 1
				fi
			else
				if dpkg-deb -b "${2}" "${_export}" 1>>/dev/null; then
					echo "${_export}"
				else
					echo "${_command}: Error: Build deb Failure"
					exit 1
				fi
			fi
		else
			i='1'
			_list="/tmp/$(_randnum '20').tmp"
			find "${2}" -maxdepth 1 -type d | sed '1d' | sort -k2n >"${_list}"
			i_max="$(cat "${_list}" | wc -l)"
			while [ "${i}" -le "${i_max}" ]; do
				_deb_n="$(cat "${_list}" | sed -n "${i}p")"
				if [ -n "${_z}" ]; then
					echo "${i}: $("${0}" -b "${_z}" "${_deb_n}")"
				else
					echo "${i}: $("${0}" -b "${_deb_n}")"
				fi
				unset _deb_n
				i="$((i+1))"
			done
			rm -rf "${_list}" &
			unset _deb_n _list
		fi
		;;
	-p|--repack)
		case "${2}" in
			xz)
				_z='xz'
				;;
			gzip)
				_z='gzip'
				;;
			zstd)
				_z='zstd'
				;;
			*)
				_skip_shift='1'
				;;
		esac
		if [ ! "${_skip_shift}" = '1' ]; then
			shift
		fi
		if [ -z "${2}" ]; then
			echo "${_command}: null"
			exit 1
		fi
		if ! dpkg-query -s "${2}" | grep -q "Package: ${2}" 1>>/dev/null 2>>/dev/null; then
			echo "${_command}: Error: Package \"${2}\" is not installed"
			exit 1
		fi
		_package="$(dpkg-query -s "${2}" | grep '^Package: ')"
		_package="${_package#*:\ }"
		_package_version="$(dpkg-query -s "${2}" | grep '^Version: ')"
		_package_version="${_package_version#*:\ }"
		_package_architecture="$(dpkg-query -s "${2}" | grep '^Architecture: ')"
		_package_architecture="${_package_architecture#*:\ }"
		if [ -z "${3}" ]; then
			_export="${_s_path}/Documents/deb/${_package}_${_package_version}_${_package_architecture}"
			_export="$(_check_exists "${_export}")"
		else
			if [ -z "$(echo "${3}" | grep '.deb$')" ]; then
				_export="$(echo "${3}/" | sed 's#//$#/#g')"
				_export="${_export}${_package}_${_package_version}_${_package_architecture}"
				_export="$(_check_exists "$(_strip "${_export}")")"
			else
				_export="$(_check_exists "$(_strip "${3}")")"
			fi
		fi
		unset _package _package_version _package_architecture
		mkdir -p "${_export}/DEBIAN"
		_dpkg_info_path="$(dpkg-query --control-path "${2}" | sed -n '1p')"
		_dpkg_info_path="${_dpkg_info_path%/*}"
		cp -a "${_dpkg_info_path}/${2}".* "${_export}/DEBIAN/"
		i='1'
		i_max="$(find "${_export}/DEBIAN/" -type f -iname ${2}* | wc -l)"
		while [ "${i}" -le "${i_max}" ]; do
			_orig_name="$(find "${_export}/DEBIAN/" -type f -iname ${2}* | sed -n '1p')"
			_patch_name="${_orig_name##*${2}.}"
			mv "${_orig_name}" "${_export}/DEBIAN/${_patch_name}"
			unset _orig _patch_name
			i="$((i+1))"
		done
		unset i i_max
		rm -f "${_export}/DEBIAN/list" "${_export}/DEBIAN/md5sums" &
		dpkg-query -s "${2}" | grep -v '^Status: ' | grep -v '^Installed-Size: ' >"${_export}/DEBIAN/control"
		if ! cat "${_export}/DEBIAN/control" | grep -q '^Description: ' ; then
			echo 'Description: An awesome MobileSubstrate tweak!' >>"${_export}/DEBIAN/control"
		fi
		if ! cat "${_export}/DEBIAN/control" | grep -q '^Maintainer: ' ; then
			echo 'Maintainer: someone' >>"${_export}/DEBIAN/control"
		fi
		i='1'
		i_max="$(cat "${_dpkg_info_path}/${2}.list" | wc -l)"
		while [ "${i}" -le "${i_max}" ]; do
			_process="$(cat "${_dpkg_info_path}/${2}.list" | sed -n "${i}p")"
			if [ -e "${_process}" ]; then
				case "$(_test "${_process}")" in
					file)
						cp -a "${_process}" "${_export}${_process}" &
						;;
					folder)
						mkdir -p "${_export}${_process}"
						chown -R $(stat --format=%u:%g "${_process}") "${_export}${_process}" &
						;;
				esac
			fi
			unset _type _process
			i="$((i+1))"
		done
		wait
		unset i i_max
		if [ -z "${_z}" ]; then
			"${0}" -b "${_export}" "${_export}.deb"
		else
			"${0}" -b "${_z}" "${_export}" "${_export}.deb"
		fi
		rm -rf "${_export}" &
		;;
	--forced-install)
		_check "${2}"
		if [ ! "${_type}" = 'deb' ]; then
			echo "${_command}: Error: not support type"
			echo "${_command}: type: ${_type}"
			exit 1
		fi
		_tmp_e="$("${0}" -e "${2}" "/tmp/$(_randnum '20')")"
		_tmp_x="$("${0}" -x "${2}" "/tmp/$(_randnum '20')")"
		_package="$(cat "${_tmp_e}/control" | grep '^Package: ' | sed 's#^Package: ##g')"
		if cat "${_dpkg_path}/status" | grep -q "^Package: ${_package}" ; then
			echo "[*] Software package \"${_package}\" has been installed and will be forcibly uninstalled..."
			"${0}" --forced-uninstall "${_package}"
		fi
		echo "[*] Write info in control to status..."
		cat "${_tmp_e}/control" >>"${_dpkg_path}/status"
		echo 'Status: install ok installed' >>"${_dpkg_path}/status"
		echo '' >>"${_dpkg_path}/status"
		rm -f "${_tmp_e}/control"
		if [ -f "${_tmp_e}/preinst" ]; then
			echo "[*] Start \"preinst\"..."
			"${_tmp_e}/preinst"
		else
			echo "[*] Not found \"preinst\", now skip..."
		fi
		cd "${_tmp_x}"
		find ./ | grep -v '^./$' | sed 's#^.##g' >>"${_tmp_x}.list"
		i='1'
		i_max="$(cat ${_tmp_x}.list | wc -l)"
		if [ ! "${i_max}" = '0' ]; then
			echo "[*] now copy file in deb..."
			while [ "${i}" -le "${i_max}" ]; do
				_process="$(cat "${_tmp_x}.list" | sed -n "${i}p")"
				case "$(_test ".${_process}")" in
					file)
						cp -a ".${_process}" "${_process}" &
						;;
					folder)
						if [ ! -e "${_process}" ]; then
							mkdir -p "${_process}"
							chown -R $(stat --format=%u:%g ".${_process}") "${_process}" &
						fi
						;;
				esac
				unset _process
				i="$((i+1))"
			done
		fi
		unset i i_max
		cd "${_pwd}"
		if [ -f "${_tmp_e}/postinst" ]; then
			echo "[*] Start \"postinst\"..."
			"${_tmp_e}/postinst"
		else
			echo "[*] Not found \"postinst\", now skip..."
		fi
		echo "[*] copy DEBIAN file..."
		cd "${_tmp_e}"
		i='1'
		i_max="$(find ./ | grep -v '^./$' | wc -l)"
		if [ ! "${i_max}" = '0' ]; then
			while [ "${i}" -le "${i_max}" ]; do
				_now_file="$(find ./ | grep -v '^./$' | sed -n "${i}p" | sed 's#^./##g')"
				if [ -n "${_now_file}" ]; then
					mv "./${_now_file}" "${_dpkg_path}/info/${_package}.${_now_file}" &
				fi
				i="$((i+1))"
				unset _now_file
			done
		fi
		cd "${_pwd}"
		echo '/.' >"${_dpkg_path}/info/${_package}.list"
		cat "${_tmp_x}.list" >>"${_dpkg_path}/info/${_package}.list"
		echo "[*] clear cache files..."
		rm -rf "${_tmp_e}" &
		rm -rf "${_tmp_x}" &
		rm -rf "${_tmp_x}.list" &
		echo "[*] Package \"${_package}\" has been forcibly installed"
		;;
	--forced-uninstall)
		if ! dpkg-query -s "${2}" 1>>/dev/null 2>>/dev/null; then
			echo "${_command}: Error: Package \"${2}\" is not installed"
			exit 1
		fi
		_package="$(dpkg-query -s ${2} | grep '^Package: ')"
		_package="${_package#*:\ }"
		if [ -f "${_dpkg_path}/info/${_package}.prerm" ]; then
			echo "[*] Start \"prerm\"..."
			"${_dpkg_path}/info/${_package}.prerm"
			rm -f "${_dpkg_path}/info/${_package}.prerm"
		else
			echo "[*] Not found \"prerm\", now skip..."
		fi
		i='2'
		i_max="$(cat "${_dpkg_path}/info/${_package}.list" | wc -l)"
		while [ "${i}" -le "${i_max}" ]; do
			_process="$(cat "${_dpkg_path}/info/${_package}.list" | sed -n ${i_max}p)"
			if [ -e "${_process}" ]; then
				case "$(_test ${_process})" in
					file)
						rm -f "${_process}" &
						;;
					folder)
						if dpkg -S "${_process}" | grep -q "^${_package}: ${_process}"; then
							rm -rf "${_process}" &
						fi
						;;
				esac
			fi
			unset _type _process
			i_max="$((i_max-1))"
		done
		unset i i_max
		wait
		if [ -f "${_dpkg_path}/info/${_package}.postrm" ]; then
			echo "[*] Start \"postrm\"..."
			"${_dpkg_path}/info/${_package}.postrm"
			rm -f "${_dpkg_path}/info/${_package}.postrm" &
		else
			echo "[*] Not found \"postrm\", now skip..."
		fi
		rm -f "${_dpkg_path}/info/${_package}.preinst" &
		rm -f "${_dpkg_path}/info/${_package}.postinst" &
		rm -f "${_dpkg_path}/info/${_package}.list" &
		rm -f "${_dpkg_path}/info/${_package}.md5sums" &
		rm -f "${_dpkg_path}/info/${_package}.triggers" &
		echo "[*] About to erase records from status..."
		_package_row="$(cat "${_dpkg_path}/status" | grep -n "^Package: ${_package}")"
		_now_row="${_package_row%%:*}"
		while [ "${_now_row}" -ne '0' ]; do
			if cat "${_dpkg_path}/status" | sed -n "${_now_row}p" | grep -q '^$' ; then
				_start_row="$((_now_row+1))"
				break
			fi
			_now_row="$((_now_row-1))"
		done
		_now_row="${_package_row%%:*}"
		while [ "${_now_row}" -ne '0' ]; do
			if cat "${_dpkg_path}/status" | sed -n "${_now_row}p" | grep -q '^$' ; then
				_end_row="${_now_row}"
				break
			fi
			_now_row="$((_now_row+1))"
		done
		sed -i.tmp "${_start_row},${_end_row}d" "${_dpkg_path}/status"
		unset _now_rows _start_row _end_row
		rm -f "${_dpkg_path}/status.tmp" &
		echo "[*] Package \"${_package}\" has been forcibly uninstalled"
		;;
	*)
		_print_help
		exit 1
		;;
esac
