#!/bin/bash

#  Description:
#
# apt wrapper to manage LliureX "pre" and "unstable" repository
# The script allows a limited set of the functionallity of apt command (search, install, etc ...)
# without permanent changes in sources.list, apt configuration, apt lists, apt cache, etc
# Run the script with no parameters to get help.
#

###############
# global vars #
###############
RELEASE=$(lsb_release -s --codename 2>/dev/null)
export RELEASE
LLX_APT_SOURCES="/var/lib/llx-apt/_@_REPO_@_/sources.list"
LLX_APT_BASE_DIR="/usr/share/llx-apt"
LLX_APT_RELEASE_SOURCES="$LLX_APT_BASE_DIR/_@_REPO_@_/sources.list"
LLX_APT_UBUNTU_SOURCES="$LLX_APT_BASE_DIR/ubuntu/sources.list"

LLX_APT_OPTIONS="Dir::Cache::Archives|/var/cache/llx-apt/_@_REPO_@_/apt-archives/ Dir::State::Lists|/var/lib/llx-apt/_@_REPO_@_/lists/ Dir::Etc::Sourcelist|$LLX_APT_SOURCES"

#LLX_APT_OPTIONS="Dir::Cache::Archives|/var/cache/llx-apt/_@_REPO_@_/apt-archives/ Dir::State::Lists|/var/lib/llx-apt/_@_REPO_@_/lists/ Dir::Cache::archives::partial|/var/cache/llx-apt/_@_REPO_@_/apt-archives/partial/ Dir::Cache::Srcpkgcache|/var/cache/llx-apt/_@_REPO_@_/apt-archives/src/ Dir::Etc::Sourcelist|$LLX_APT_SOURCES"

LLX_APT_NONROOT_CMDS="list | search | show | policy | rdepends | download"
LLX_APT_ROOT_CMDS="update | install | remove | clean"
LLX_APT_CMDS="$LLX_APT_NONROOT_CMDS | $LLX_APT_ROOT_CMDS"
LLX_APT_RELEASES0="pre|unstable"

# use only available releases
LLX_APT_RELEASES=""
for r in $(echo "$LLX_APT_RELEASES0" |tr "|" " ") ; do
	if [ -d "$LLX_APT_BASE_DIR/$r" ] ; then
		LLX_APT_RELEASES="$LLX_APT_RELEASES|$r"
	fi
done
LLX_APT_RELEASES="${LLX_APT_RELEASES#*|}"

LLX_ROOT_REQUIRED=""

# export this variable for dry-run
#LLX_APT_DEBUG=""

#############
# functions #
#############
die(){
        TYPE="ERROR"
        if [ "$#" -gt 1 ] ; then
                TYPE="$1"
                shift
        fi
        printf "\n\t${TYPE}: " >&2
        while [ "$1" ] ; do
                echo "** $1 **" >&2
                shift
        done
		usage
        echo "" >&2

        exit 1
}

usage(){
        printf "\r      \n \
        Usage\n
		$(basename "$0") REPOSITORY[+ubuntu] [--no-update] [--no-pinning] [OPTIONS ...] COMMAND [ARGUMENTS ...]\n \
	   \n\t\tREPOSITORY: Mandatory. {pre|unstable}. Additionally add +ubuntu to include ubuntu repositories\n \
	   \t--no-update: Doesn't update apt information\n \
	   \t--no-pinning: Disable pinning\n \
       \tOPTIONS: [*ANY APT OPTION*]\n \
	   \tCOMMAND: {$LLX_APT_CMDS}\n 
        Example\n \
		$(basename "$0") pre+ubuntu policy firefox\n"
}

expand_repo(){
	echo "$1" |sed -e "s%_@_REPO_@_%$2%g"
}

create_environment(){
	# create required dirs
	for D0 in $LLX_APT_OPTIONS ; do
		D1="${D0#*|}"
		DIRNAME="${D1%/*}"
		mkdir -p "$DIRNAME"
	done

	# create sources.list from the original file
	:> "$LLX_APT_SOURCES"
	for f in /etc/apt/sources.list $LLX_APT_RELEASE_SOURCES ; do
		if [ -r "$f" ] ; then
			cat "$f" | envsubst >> "$LLX_APT_SOURCES"
		fi
	done

}

main(){
	# sanity checks

	[ "$1" ] || die

	[ $(echo $@ | grep -c "help") -gt 0 ] && die

	REPO="${1%+*}"

	if echo "|${LLX_APT_RELEASES}|" |tr -d " " |grep -qF "|$REPO|" ; then
		LLX_APT_SOURCES="$(expand_repo "$LLX_APT_SOURCES" "$REPO")"
		LLX_APT_OPTIONS="$(expand_repo "$LLX_APT_OPTIONS" "$REPO")"
		LLX_APT_RELEASE_SOURCES="$(expand_repo "$LLX_APT_RELEASE_SOURCES" "$REPO")"
	else
		die "Invalid release $REPO"
	fi
	if echo "$1" | grep -q "+ubuntu$" ; then
		LLX_APT_RELEASE_SOURCES="$LLX_APT_RELEASE_SOURCES $LLX_APT_UBUNTU_SOURCES"
	fi
	export LLX_APT_SOURCES LLX_APT_OPTIONS LLX_APT_RELEASE_SOURCES

	shift
	# preserve user arguments
	USER_CMD_ARGS="$@"

	# search for command string
	while echo "x$1" | grep -q "^x-" ; do
		shift
	done
	USER_CMD="$1"

	# check against command list
	if ! echo "|$LLX_APT_CMDS|" |tr -d " " |grep -qF "|$USER_CMD|" ; then
		die "Unknow command $USER_CMD"
	fi

	# check against root command list
	if echo "|$LLX_APT_ROOT_CMDS|" |tr -d " " |grep -qF "|$USER_CMD|" ; then
		LLX_ROOT_REQUIRED="Y"
	fi

	if [ -z "$LLX_APT_DEBUG" ] && [ "$LLX_ROOT_REQUIRED" ]; then
		# test root privileges
		[ $(id -u) -eq 0 ] || die "root privileges required"
	fi

	LLX_NO_UPDATE=$(echo $USER_CMD_ARGS | grep -o [-]*no-update)
	USER_CMD_ARGS=${USER_CMD_ARGS/$LLX_NO_UPDATE/}
	LLX_NO_PINNING=$(echo $USER_CMD_ARGS | grep -o [-]*no-pinning)
	USER_CMD_ARGS=$(echo ${USER_CMD_ARGS/$LLX_NO_PINNING/} | xargs)

	# Build custom apt options
	LLX_APT_EXTRA=""
	for OP0 in $LLX_APT_OPTIONS ; do
		#OP="$(echo "$OP0" |sed -e "s%|%='%;s%$%'%")"
		OP="$(echo "$OP0" |sed -e "s%|%=%")"
		LLX_APT_EXTRA="$LLX_APT_EXTRA -o $OP"
	done
	if [ "$LLX_APT_DEBUG" ] ; then
		echo "DEBUG: Command to run"
		echo "       apt $LLX_APT_EXTRA $USER_CMD_ARGS"
	else
		if [ "$LLX_ROOT_REQUIRED" ] ; then
			if [ ${#LLX_NO_PINNING} -gt 0 ]
			then
				#Remove pinning, remember to restore it
				echo "#############################"
				echo "#---------------------------#"
				echo "#_________ATTENTION_________#"
				echo "#         ATTENTION         #"
				echo "#---------------------------#"
				echo "#############################"
				echo "Removing pinning is dangerous and could let to troubles"
				echo "Only continue if you're sure that pinning really must be removed"
				echo "ONLY IF YOU'RE SURE"
				echo -n "Are you sure? y/[n] "
				read SURE
				[[ $SURE != "y" ]] && die "Operation aborted"
			fi
			create_environment || die "Failed to create apt environment"
			if [[ $USER_CMD != "update" ]] && [ ${#LLX_NO_UPDATE} -eq 0 ]
			then
				apt $LLX_APT_EXTRA update 2> >(grep -v 'W: .*' >&2)
			fi
			#Pinning option must be added after repositories are updated
			if [ ${#LLX_NO_PINNING} -gt 0 ]
			then
				LLX_APT_EXTRA=$LLX_APT_EXTRA" -o APT::Default-release=$RELEASE"
			fi
		else
			echo "If you continue without updating the repositories the info provided could be unaccurated."
			echo -n "Continue without updating repository information? [y]/n "
			read SURE
			[[ $SURE != "y" ]] && sudo apt $LLX_APT_EXTRA update 2> >(grep -v 'W: .*' >&2)
		fi
		# use a dirty trick to avoid output of warnings related to duplicated lines in sources.list
		apt $LLX_APT_EXTRA $USER_CMD_ARGS 2> >(grep -v 'W: .*' >&2)
	fi
}

################
# main program #
################
rc=0 
main "$@" || rc=$?
exit $rc

