# !/bin/bash
# Fix Cydia repository errors
# v1.6.7 - 22nd August 2010 (Contact author: @Secretss_ on Twitter)
#
# Thanks go to MadHouse and Helpmy360isEMO.

#########################################################################################00#
function help {
	echo -e "Usage: cyfix repo.url.here\n\t-to remove repository"
	echo -e "Usage: cyfix -l\n\t-to list all installed repos"
	echo -e "Usage: cyfix -d\n\t-for multi-repo removal"
	echo -e "Usage: cyfix -u\n\t-to update Cyfix"
	echo -e "Usage: cyfix -h\n\t-to display this text"
	echo -e "v1.6.7 Written by Secretss\nContact Secretss[C4iD] on Rizon IRC server\nor @Secretss_ on Twitter.\n"
}

#########################################################################################00#
if [ "$(id -u)" != "0" ]; then
	echo -e "\nThis script must be run as root user.\n"
	exit
fi

if [ ! -e /usr/bin/wget ] || [ ! -e /usr/bin/plutil ] || [ ! -e /bin/sed ] || [ ! -e /usr/bin/awk ] || [ ! -e /bin/grep ] || [ ! -e /usr/bin/gettext ]; then
	echo -n "Installing necessary tools... "
	if [ ! -e /usr/bin/apt-get ]; then
	     echo -e "\nUnable to automatically install tools,\nplease install APT 0.7 Strict from Cydia.\n"
	     exit 1
	fi
	if [ ! -e /usr/bin/plutil ]; then
	     apt-get -qq install com.ericasadun.utilities > /dev/null 2>&1
	     if [ ! -e /usr/bin/plutil ]; then
		  echo -e "\nUnable to install tools.\nAre you connected to the Internet?"
		  exit 1
	     fi
	fi
	if [ ! -e /bin/sed ]; then
	     apt-get -qq install sed > /dev/null 2>&1
	     if [ ! -e /bin/sed ]; then
		  echo -e "\nUnable to install tools.\nAre you connected to the Internet?"
		  exit 1
	     fi
	fi
	if [ ! -e /usr/bin/awk ]; then
	     apt-get -qq install gawk > /dev/null 2>&1
	     if [ ! -e /usr/bin/awk ]; then
		  echo -e "\nUnable to install tools.\nAre you connected to the Internet?"
		  exit 1
	     fi
	fi
	if [ ! -e /bin/grep ]; then
	     apt-get -qq install grep > /dev/null 2>&1
	     if [ ! -e /bin/grep ]; then
		  echo -e "\nUnable to install tools.\nAre you connected to the Internet?"
		  exit 1
	     fi
	fi
	if [ ! -e /usr//bin/gettext ]; then
	     apt-get -qq install gettext > /dev/null 2>&1
	     if [ ! -e /bin/grep ]; then
		  echo -e "\nUnable to install tools.\nAre you connected to the Internet?"
		  exit 1
	     fi
	fi
	if [ ! -e /usr/bin/wget ]; then
	     apt-get -qq install wget > /dev/null 2>&1
	     if [ ! -e /usr/bin/wget ]; then
		  echo -e "\nUnable to install tools.\nAre you connected to the Internet?"
		  exit 1
	     fi
	fi
	echo -e "Done.\n"
fi

cd /usr/bin
before=$(md5sum cyfix)
echo -n "Checking for updates..."
wget -q http://dl.dropbox.com/u/1838452/cyfix -O "/usr/bin/cyfix1"
mv -f cyfix1 cyfix
chmod 755 cyfix
if [ "$before" != "$(md5sum cyfix)" ]; then
	echo -e " Updated.\nPlease run Cyfix again.\n"
	exit
else
	echo -e " Not updated.\n"
fi

#########################################################################################0F#
CyfixDir="/tmp/Cyfix"
rm -rf $CyfixDir
mkdir $CyfixDir

function repocheck() {
	if [ "$#" = "1" ] && [ ! "$reponums" ]; then
		repo=$1
		if [ "$repo" = "$(cat $CyfixDir/fullrepolist | grep -m 1 "$repo" | awk '{print $2}')" ]; then
			if [ "$(cat $CyfixDir/fullrepolist | grep "$repo" | awk '{print $1}')" -gt "$point" ]; then
				status=default
				default1=yes
			else
				default1=no
			fi
		else
			status=dne
			echo -e "\nRepository not found. Did you type it right?\n"
			exit
		fi
	else
		array=($reponums)
		k=0
		for i in $(seq 0 $((${#array[*]}-1))); do
			number=$(echo "${array[$i]}" | grep -E [0-9])
			if [ ! "$number" ]; then
				echo -e "\nPlease input integers only.\n"
				exit
			elif [ "${array[$i]}" -gt "$num" ]; then
				echo -e "\nInvalid selection.\n"
				exit
			elif [ "${array[$i]}" -gt "$point" ]; then
				default2=yes
				defaultrepo[$k]=${array[$i]}
				let k+=1
			fi
		done
		if [ "$default2" != "yes" ]; then
			default2=no
		fi
	fi
}

function listrepo {
	rm -rf $CyfixDir
	mkdir $CyfixDir

	cat /etc/apt/sources.list.d/cydia.list | grep "http://" | awk '{print $2}' | sed -e "s:http\://::g" > $CyfixDir/repo-user
	point=0
	while read line; do
		let point+=1
		echo -e "$point $(echo -n $line | head -c -1)"
	done < $CyfixDir/repo-user > $CyfixDir/repo-user1
	mv -f $CyfixDir/repo-user1 $CyfixDir/repo-user

	for item in $(ls /etc/apt/sources.list.d/); do
		if [ "$item" = "saurik.list" ] || [ "$item" = "cydia.list" ]; then
			continue
		fi
		cat /etc/apt/sources.list.d/$item | grep "http://" | awk '{print $2}' | sed -e "s:http\://::g" >> $CyfixDir/repo-default
	done
	if [ -e /etc/apt/sources.list.d/saurik.list ] && [ $(grep -c apt.saurik.com /etc/apt/sources.list.d/saurik.list) -gt 0 ]; then
		echo -e "apt.saurik.com/" >> $CyfixDir/repo-default
	else
		echo -e "Error: Saurik's Telephoreo repository not found!" >> $CyfixDir/repo-default
	fi
	let num=$point
	while read line; do
		if [ ${#line} -gt 2 ]; then
			let num+=1
			echo -e "$num $(echo -n $line | head -c -1)"
		fi
	done < $CyfixDir/repo-default > $CyfixDir/repo-default1
	mv -f $CyfixDir/repo-default1 $CyfixDir/repo-default

	echo -e "$(cat $CyfixDir/repo-user)" > $CyfixDir/fullrepolist
	echo -e "$(cat $CyfixDir/repo-default)" >> $CyfixDir/fullrepolist

	if [ "$(cat $CyfixDir/fullrepolist)" = "1 " ]; then
		echo -e "No repositories found."
		exit
	else
		 echo -e "$(cat $CyfixDir/fullrepolist)"
	fi
	echo  
}

function processrepourl() {
	repo=$1
	if [ $(echo -n $repo | tail -c -1) == "/" ]; then
		repo=$(echo -n $repo | head -c -1)
	fi
	if [ "${repo:0:7}" = "http://" ]; then
		repo=$(echo $repo | sed -e 's:http\://::g')
	fi 
	expand=$(echo $repo | sed 's/\(.\)/\1 /g')
	array1=($expand)

	j=0
	for i in $(seq 0 $((${#array1[*]} - 1))); do
		b[$j]=${array1[$i]}
		c[$i]=${array1[$i]}
		if [ ${array1[$i]} == "/" ]; then
			b[$j]="\\"
			c[$i]="_"
			let j+=1
			b[$j]="/"
		fi
		let j+=1
		array1[$i]=''
	done
	
	reponame=$(echo ${b[*]} | tr -d ' ')
	filename=$(echo ${c[*]} | tr -d ' ')
	file6=$(grep -l $repo /etc/apt/sources.list.d/*.list)

	expand=''
	for i in $(seq 0 $((${#b[*]} + ${#c[*]}))); do
		b[$i]=''
		c[$i]=''
	done

	repocheck "$repo"
}

function removerepo() {
	repo=$1
	processrepourl $repo
	
	ls /var/lib/apt/lists/* > $CyfixDir/log
	ls /var/lib/apt/lists/partial/* >> $CyfixDir/log
	grep /var/lib/apt/lists $CyfixDir/log > $CyfixDir/log1
	mv -f $CyfixDir/log1 $CyfixDir/log
	
	files=$(grep $filename $CyfixDir/log)
	for word in $files; do
		rm -f $word
	done

	if [ "$default1" = "no" ]; then
		cat /etc/apt/sources.list.d/cydia.list | grep -v $repo > /etc/apt/sources.list.d/cydia.list1
		mv -f /etc/apt/sources.list.d/cydia.list1 /etc/apt/sources.list.d/cydia.list
		plutil -convert xml1 /var/lib/cydia/metadata.plist > /dev/null 2>&1
		start="<key>deb:http:\/\/$reponame\/:.\/<\/key>"
		stop="<\/dict>"
		echo -e "$(cat /var/lib/cydia/metadata.plist | sed -e "/$start/,/$stop/ s/.*//")" > /var/lib/cydia/metadata.plist1
		mv -f /var/lib/cydia/metadata.plist1 /var/lib/cydia/metadata.plist
	elif [ "$default1" = "yes" ]; then
		if [ -f $file6 ] && [ "$file6" != "/etc/apt/sources.list.d/cydia.list" ]; then
			rm -f "$file6"
		fi
	fi

	echo -e "Removed $repo."
}

function removerepos {
	reponums=''
	echo "Executing repository removal... "
	for reponum in ${array[*]}; do
		repo=$(cat $CyfixDir/fullrepolist | grep -m 1 "$reponum " | awk '{print $2}')
		removerepo $repo
	done
}

#########################################################################################01#
if [ $# -lt 1 ] || [ "$1" = "-h" ]; then
	help
	exit
elif [ $# -gt 1 ]; then
	echo -e "Only one repository at a time please."
	exit
fi

if [ "$1" = "-u" ]; then
	cd /usr/bin
	before=$(md5sum cyfix)
	echo -e "\nChecking for updates."
	wget -N -q http://dl.dropbox.com/u/1838452/cyfix
	chmod 755 cyfix
	if [ "$before" != "$(md5sum cyfix)" ]; then
		echo -e "Cyfix has been successfully updated.\n"
	else
		echo -e "No updates available.\n"
	fi
	exit
fi

if [ "$1" = "-l" ]; then
	listrepo
	exit
fi

if [ "$1" = "-d" ]; then
	listrepo
	echo -e "Please enter the numbers corresponding to\nthe repositories you want to remove.\nSeparate your numbers by a space:"
	read reponums
	if [ ! "$reponums" ]; then
		echo No input detected.
		exit
	fi
	echo -e "\nWARNING:\nPlease make sure Cydia is not running.\n"
	echo -n "Processing repositories... "
	repocheck $reponums
	if [ "$default2" = "yes" ]; then
		echo -e "\nDefault repository/ies detected:\n${defaultrepo[*]}\nProceed with removal? (Y/N):"
		read prompt2
		if [ "$(echo $prompt2 | tr A-Z a-z)" = "$(echo Y | tr A-Z a-z)" ]; then
			removerepos
		else
			echo -e "Have a nice day, then.\n"
			exit
		fi
	else
		echo Done.
		removerepos
	fi
	echo -e "Done.\n\nListing remaining repositories:"
	listrepo
	exit
fi

if [ "$#" = "1" ]; then
	repo=$1
	listrepo > /dev/null 2>&1
	echo -e "\nWARNING:\nPlease make sure Cydia is not running.\n"
	echo -n "Processing repository... "
	processrepourl "$repo"
	if [ "$default1" = "yes" ]; then
		echo -e "\nThis is a default Cydia repository,\nare you sure you want to remove it? (Y/N):"
		read prompt1
		if [ "$(echo $prompt1 | tr A-Z a-z)" = "$(echo Y | tr A-Z a-z)" ]; then
			echo -n "Executing repository removal... "
			removerepo "$repo"
		else
			echo -e "Have a nice day, then.\n"
			exit
		fi
	else
		echo Done.
		echo -n "Executing repository removal... "
		removerepo "$repo"
	fi
	echo -e "Done.\n"
fi

exit