#!/bin/bash

PROG="${0##*/}"

create_apt_cache_dir()
{
	local cache="$1"
	[ -d "$cache/archives/partial/" ] ||
		mkdir -p "$cache/archives/partial/"
	[ -f "$cache/archives/lock" ] ||
		touch "$cache/archives/lock"
	chown :rpm -R "$cache"
	chmod 2770 "$cache"
	chmod 2770 "$cache/archives"
	chmod 2770 "$cache/archives/partial"
	chmod 2640 "$cache/archives/lock"
}

create_apt_lists_dir()
{
	local lists="$1"
	[ -d "$lists/partial/" ] ||
		mkdir -p "$lists/partial/"
	[ -f "$lists/lock" ] ||
		touch "$lists/lock"
}

clean_apt_cache_dir()
{
	local cache="$1"
	if [ -d "$cache/archives/" ]; then
		echo rm -f "$cache/archives/"*.rpm
	fi
}

clean_apt_lists_dir()
{
	local lists="$1"
	if [ -d "$lists" ]; then
		echo rm -f "$lists/"*_base_*
	fi
}

cache_dir_regexp='^Dir::Cache .*;$'
cache_dir_subst='s/^Dir::Cache "\(.*\)";$/\1/'
cache_dir_slash='s|^[^/]|/&|'
cache_dir_append='s|[^/]$|&/|'
cache_dir="$(apt-config dump | grep "$cache_dir_regexp" | sed -e "$cache_dir_subst" -e "$cache_dir_slash" -e "$cache_dir_append")"

state_dir_regexp='^Dir::State .*;$'
state_dir_subst='s/^Dir::State "\(.*\)";$/\1/'
state_dir_slash='s|^[^/]|/&|'
state_dir_append='s|[^/]$|&/|'
state_dir="$(apt-config dump | grep "$state_dir_regexp" | sed -e "$state_dir_subst" -e "$state_dir_slash" -e "$state_dir_append")"

lists_dir_regexp='^Dir::State::lists .*;$'
lists_dir_subst='s/^Dir::State::lists "\(.*\)";$/\1/'
lists_dir_slash="s|^[^/]|$state_dir&|"
lists_dir="$(apt-config dump | grep "$lists_dir_regexp" | sed -e "$lists_dir_subst" -e "$lists_dir_slash")"

create_directories()
{
	create_apt_cache_dir "$cache_dir"
	create_apt_lists_dir "$lists_dir"
}

clean_directories()
{
	clean_apt_cache_dir "$cache_dir"
	clean_apt_lists_dir "$lists_dir"
}

action=

usage()
{
	[ "$1" = 0 ] || exec >&2
	cat <<EOF
Usage: $PROG <option>

Valid options are:
-c, --create                            create apt cache directories;
-x, --clean                             clean apt cache directories;
-h, --help                              show this text.

Found directories:
 Cache directory is $cache_dir.
 State directory is $state_dir.
 State::lists directory is $lists_dir.
EOF
	[ -n "$1" ] && exit "$1" || exit
}

TEMP=`getopt -n $PROG -o cxh -l create,clean,help -- "$@"` || usage
eval set -- "$TEMP"

while :; do
	case "$1" in
		-c|--create) shift; action="create"
			;;
		-x|--clean) shift; action="clean"
			;;
		-h|--help) usage 0
			;;
		--) shift; break
			;;
		*) echo "$PROG: unrecognized option: \"$1\"" >&2; exit 1
			;;
	esac
done

case "$action" in
	create) create_directories
		;;
	clean) clean_directories
		;;
	*) usage
		;;
esac
