#!/bin/bash
x=1
pts=/usr/share/koffe/
pathto=$PWD
reset="\e[0m"
green="\e[0;32m"
optdep=0
quiet=0
pactree_command="pactree -su "
pacout=/dev/stdout
clearcomm='clear ; outapp'
wgetargs="-q --show-progress"
quiet_flag="-q"
verbose_flag=""
outapp(){
	for outapp in $prog
	do
		if [[ $outapp == $app ]];
		then
			echo -ne "${green}$outapp${reset} "
		else
			echo -ne "$outapp "
		fi
	done
	echo
	echo ">-------------------------------------------------<"
	echo
}
if [ $1 ]; 
then
    for argument in $@
    do
        if [[ $argument == "--help" ]];
        then
            echo "koffe is a tool for making simple and intuitive offline archlinux installer iso's" 
        	echo 
			echo "koffe [options] <out folder>"
			echo 
            echo "Flags:"
			echo
			echo "	koffe -v                  --> verbose output"
			echo
            echo "	koffe --pacs=Prog1,Prog2  --> starts koffe and creates" 
            echo "                                an iso with the programs Prog1 and Prog2"
            echo "                                IMPORTANT: Separate the progs with commas"
            echo "                                and do not use spaces"
            echo
            echo "	koffe --clean             --> cleans building dirs after unexpected" 
            echo "                                exit or unsuccesful iso generation. Will"
            echo "                                nullify any other args parsed with it and will"
            echo "                                not create an iso"
            echo
            echo "	koffe --scripts=/foo/bar  --> copies the scripts in the specified path"
            echo "                                and uses them instead of the default koffe"
            echo "                                scripts in /usr/share/koffe/. Avoid paths with spaces"
			echo
			echo "	koffe --opt               --> Also downloads optional dependencies for packages"
			echo "                                Use for a more complete installation."
			echo
            exit
        fi
        if [[ $(echo $argument | cut -f 1 -d '=') == "--pacs" ]];
        then
            declare -a prog
            x=0
            prog=$(echo $argument | cut -f 2 -d '=')
            prog=${prog//,/ }
            echo $prog
        fi
        if [[ $(echo $argument | cut -f 1 -d '=') == "--scripts" ]];
        then
            pts=$(echo $argument | cut -f 2 -d '=')
        fi
        if [[ $argument == "--clean" ]];
        then
            if [[ $(whoami) == root ]];
            then
                rm -rf /tmp/koffe_workdir
                rm -rf /tmp/koffe/rootfs/airootfs/root/*
                rm -rf /tmp/koffe/
                exit
            fi
        fi
		if [[ $argument == "--opt" ]];
		then
			optdep=1
			pactree_command="pactree -suo "
		fi
		if [[ $argument == "-v" ]];
		then
			verbose=1
			pacout=/dev/stdout
			clearcomm="echo"
			wgetargs=""
			quiet_flag=""
			verbose_flag="-v"
		fi

    done
fi
if [ $(whoami) != root ];
then
    echo
    echo WARNING: the program needs to be ran as root
    echo $prog
fi

for lastarg; do :; done
#GET LAST ARG ^^

if [[ $lastarg == -* ]];
then
	#argument, no outfile, use PWD
	pathto=$PWD
else
	#outfile
	pathto=$(realpath $lastarg)
fi


if [ $(whoami) == root ];
then
	#updating the database is required for pacman to resolve the latest links to packages
	echo "Running 'pacman -Syu'"
	pacman -Suy > $pacoutput
	clear
    mkdir /tmp/koffe/
    mkdir /tmp/koffe/l/
    mkdir /tmp/koffe/n/
    mkdir /tmp/koffe/aur/
    mkdir /tmp/koffe/aurbg/
	mkdir /tmp/koffe/rootfs/
	cp -ar /usr/share/archiso/configs/releng/* /tmp/koffe/rootfs/.
    mkdir /tmp/koffe/rootfs/airootfs/root/pkg/
    cp $pts/* /tmp/koffe/rootfs/airootfs/root/
    echo '' > /tmp/koffe/rootfs/airootfs/root/install.list
    mkdir /tmp/koffe_workdir
    mkdir ~/out
    rm -rf /var/cache/pacman/pkg/*

	if [[ x == 1 ]];
    then
        declare -a prog
        prog=$(whiptail --inputbox "Please enter all the programs to be included in the installer separated by a space, you can also include package groups like gnome or xorg or AUR packages" 0 0 4 3>&1 1>&2 2>&3 3>&-)
    fi
	prog="$prog libnewt"


    for app in $prog
    do
		clear
		outapp
		PACAUR=0
        variable=$(pacman -Sg $app)
        if [[ $variable == '' ]];
        then
            #simple package ex:base
			aurornot=$($pactree_command $app 2>&1 >/dev/null | cut -f 1 -d ':')
			if [[ $auronnot != "error" ]];
			then
			    $pactree_command $app > /tmp/koffe/n/$app
            	pacman -Spdd --noconfirm - < /tmp/koffe/n/$app > /tmp/koffe/l/$app
            	echo $app >> /tmp/koffe/rootfs/airootfs/root/install.list
				if [[ $optdep == 1 ]];
				then
					#ADD OPTIONAL DEPS TO INSTALL LIST
					pactree -suo $app > /tmp/koffe/with_opt
					pactree -su $app > /tmp/koffe/wout_opt
					prog="$prog $(grep -Fxvf /tmp/koffe/wout_opt /tmp/koffe/with_opt | cut -d ':' -f 1 | cut -d '>' -f 1 | tr '\n' ' ')"
				fi
            	wget $wgetargs -nc -i /tmp/koffe/l/$app -P /tmp/koffe/rootfs/airootfs/root/pkg/
				$clearcomm
			fi
			
			if [[ $aurornot == "error" ]];
			then
				PACAUR=1
			fi
        fi
        if [[ $variable != '' ]];
        then
            #group package ex:gnome
            pacman -Sg $app > /tmp/koffe/generaltemp
            cut -f 2- -d ' ' /tmp/koffe/generaltemp > /tmp/koffe/grlist
            grlist=$(cat /tmp/koffe/grlist)
            echo '' > /tmp/koffe/grtree
            for component in $grlist
            do
                $pactree_command $component >> /tmp/koffe/grtree
                echo $component >> /tmp/koffe/rootfs/airootfs/root/install.list
				if [[ $optdep == 1 ]];
				then
					#ADD OPTIONAL DEPS TO INSTALL LIST
					pactree -suo $component > /tmp/koffe/with_opt
					pactree -su $component > /tmp/koffe/wout_opt
					prog="$prog $(grep -Fxvf /tmp/koffe/wout_opt /tmp/koffe/with_opt | cut -d ':' -f 1 | cut -d '>' -f 1 | tr '\n' ' ')"
				fi
		
            done
            pacman -Spdd --noconfirm - < /tmp/koffe/grtree > /tmp/koffe/grlinks
            wget $wgetargs -nc -i /tmp/koffe/grlinks -P /tmp/koffe/rootfs/airootfs/root/pkg/
			$clearcomm
        fi
		if [[ $PACAUR == 1 ]];
		then
			echo "AUR PACKAGE! BEWARE"
        	mkdir /tmp/koffe/home
        	usermod -d /tmp/koffe/home/ nobody
        	git clone https://aur.archlinux.org/$app /tmp/koffe/aurbg/$app
        	chown -hR nobody /tmp/koffe/
        	cd /tmp/koffe/aurbg/$app
        	echo $app >> /tmp/koffe/rootfs/airootfs/root/install.list
        	declare -a bb
        	bb=$(cat /tmp/koffe/aurbg/$app/.SRCINFO | grep depends | cut -f 2 -d '=' | cut -f 1 -d '>' | cut -f 1 -d ':')
        	for depend in $bb
        	do
				aurdep_aur=$($pactree_command $depend 2>&1 >/dev/null | cut -f 1 -d ':')
				
				if [[ $aurdep_aur != "error" ]];
				then
            	pactree -su $depend > /tmp/koffe/n/$depend
            	pacman -Spdd --noconfirm - < /tmp/koffe/n/$depend > /tmp/koffe/l/$depend
            	wget $wgetargs -nc -i /tmp/koffe/l/$depend -P /tmp/koffe/rootfs/airootfs/root/pkg/
				$clearcomm
				fi
				if [[ $aurdep_aur == "error" ]];
				then
				git clone https://aur.archlinux.org/$depend /tmp/koffe/aurbg/$depend
            	chown -hR nobody /tmp/koffe/$depend
            	cd /tmp/koffe/aurbg/$depend
            	sudo -u nobody makepkg --noconfirm --skippgpcheck
            	cp /tmp/koffe/aurbg/$depend/*.pkg.tar.zst /tmp/koffe/rootfs/airootfs/root/pkg
				$clearcomm
				fi
        	done
			declare -a bbm
        	bbm=$(cat /tmp/koffe/aurbg/$app/.SRCINFO | grep makedepends | cut -f 2 -d '=' | cut -f 1 -d '>' | cut -f 1 -d ':')
        	for depend in $bbm
        	do
				echo "--> Install $depend (needed to build the AUR package)?"
				pacman -S $depend --noconfirm > $pacout
			done
			sudo -u nobody makepkg --noconfirm --skippgpcheck > $pacout
        	cp /tmp/koffe/aurbg/$app/*.pkg.tar.zst /tmp/koffe/rootfs/airootfs/root/pkg
		fi
    done
	clear
	echo -e "${green}-->${reset} Building REPO image"
    repo-add $quiet_flag /tmp/koffe/rootfs/airootfs/root/pkg/koffe.db.tar.gz /tmp/koffe/rootfs/airootfs/root/pkg/* > $pacout
	echo "Done!"
	echo
	echo "bash ~/install" > /tmp/koffe/rootfs/airootfs/root/.zshrc
	echo -e "${green}-->${reset} Making ISO image (might take a while)"
    mkarchiso $verbose_flag -L "koffe" -w /tmp/koffe_workdir -o $pathto /tmp/koffe/rootfs/ 2>&1 1>$pacout
	echo "Done!"
	echo
	echo "--> Cleaning up"
    rm -rf /tmp/koffe_workdir
    rm -rf /tmp/koffe/rootfs//airootfs/root/*
    rm -rf /tmp/koffe/
	echo "Done!"
	echo
	echo "quit"
fi
      
