#!/bin/bash

cd "$(dirname $0)"

#variables
IPAPATH="$1"

if [ "$1" == "-h" ] || [ "$1" == "-help" ] || [ "$1" == "help" ]
then
	echo "not yet hehe"
	exit
fi

echo "          ,--.   .     .   "
echo ". ,-. ,-.    / ,-| ,-. |-. "
echo "| | | ,-| ,-'  | | |-' | | "
echo "' |-' \`-^ \`--- \`-' \`-' \`-' "
echo -e "  |   \033[94mversion 1.0.4        "
echo -e "\033[0m  |   \033[94mby rullinoiz\033[0m"
echo -e "_,^._______________________\n"

#check if IPAPATH was not specified
if [ -z "$IPAPATH" ]
then
	#ask for it
	read -p 'Enter path of IPA file to convert: ' IPAPATH
fi

#check if relative path
if [ "." == "$(dirname $IPAPATH)" ]
then
	echo -e "\033[94mipa2deb\033[0m: please use an absolute path and not a relative path, that kind of screws up the whole script"
	exit
fi

#check if metadata was set
if [ -z "$2" ]
then
	#if not, then ask for each one
	read -p 'Package Identifier: '  IDENTIFIER
	echo "Package: $IDENTIFIER" > /tmp/stuff.tmp
	read -p 'Name: ' NAME
	echo "Name: $NAME" >> /tmp/stuff.tmp
	read -p 'Version: ' VERSION
	echo "Version: $VERSION" >> /tmp/stuff.tmp
	read -p 'Description: ' DESCRIPTION
	echo "Description: $DESCRIPTION" >> /tmp/stuff.tmp
	read -p 'Maintainer: ' MAINTAINER
	echo "Maintainer: $MAINTAINER" >> /tmp/stuff.tmp
	read -p 'Author: ' AUTHOR
	echo "Author: $AUTHOR" >> /tmp/stuff.tmp
	read -p 'Section: ' SECTION
	echo "Section: $SECTION" >> /tmp/stuff.tmp
	echo "Architecture: iphoneos-arm" >> /tmp/stuff.tmp

	METADATA="$(cat /tmp/stuff.tmp)"
	echo "$METADATA"
	ARCH="iphoneos-arm"
else

	METADATA="$(cat $2)"
	echo "$METADATA" > /tmp/stuff.tmp

	WORDTOREMOVE="Package: "
	IDENTIFIER="$(grep "$WORDTOREMOVE" /tmp/stuff.tmp)"
	IDENTIFIER=${IDENTIFIER//$WORDTOREMOVE/}

	WORDTOREMOVE="Architecture: "
	ARCH="$(grep "$WORDTOREMOVE" /tmp/stuff.tmp)"
	ARCH=${ARCH//$WORDTOREMOVE/}

	WORDTOREMOVE="Version: "
	VERSION="$(grep "$WORDTOREMOVE" /tmp/stuff.tmp)"
	VERSION=${VERSION//$WORDTOREMOVE/}

fi

rm /tmp/stuff.tmp

cp "$(dirname $IPAPATH)/$(basename $IPAPATH)" /tmp/lmao.zip

unzip /tmp/lmao.zip -d /tmp/lmao/
rm /tmp/lmao.zip

mkdir "/tmp/test"
mkdir "/tmp/test/Applications"
mkdir "/tmp/test/DEBIAN"

printf "$METADATA" > /tmp/test/DEBIAN/control
printf "\n" >> /tmp/test/DEBIAN/control
cat /tmp/test/DEBIAN/control

mv -f /tmp/lmao/Payload/*/ /tmp/test/Applications/
rm -rf /tmp/lmao

printf "\n\n"
echo -e "\033[94mipa2deb: \033[0mbuilding package in $(dirname $IPAPATH)/${IDENTIFIER}_${VERSION}_${ARCH}.deb"
echo "This might take a while..."
t="$(dpkg -b /tmp/test)"
mv -f /tmp/test.deb "$(dirname $IPAPATH)/${IDENTIFIER}_${VERSION}_${ARCH}.deb"
rm -rf /tmp/test
echo -e "\033[94mipa2deb\033[0m: if there weren't any errors, it should've worked"
echo -e "\033[94mipa2deb\033[0m: if there is no file in the current directory, it's probably in /tmp/test.deb"
