#!/usr/bin/env bash # Apt-P2P Clean # # Douglas Thrift # # $Id$ # Copyright 2010 Douglas Thrift # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. function usage() { cat <<-EOF Usage: $program [options] Options: -a ARCHIVE, --archive=ARCHIVE set the APT archive directory (default: $_apt_archive) -c CACHE, --cache=CACHE set the Apt-P2P cache directory (default: $_apt_p2p_cache) -e, --execute clean up the Apt-P2P cache -h, --help show this help message and exit -n, --no-execute show what would be done to clean up the Apt-P2P cache -v, --version show version information and exit EOF exit $@ } function version() { echo "$program $version" exit } program=`basename $0` version='1.0.4' apt_p2p_cache='/var/cache/apt-p2p/cache' _apt_p2p_cache="$apt_p2p_cache" apt_archive='/var/cache/apt/archives' _apt_archive="$apt_archive" args=`getopt -l 'archive:,cache:,execute,help,no-execute,version' -n "$program" -o 'a:c:ehnv' -- "$@"` value=$? [[ $value != 0 ]] && usage $value eval set -- "$args" unset args until [[ "$1" == -- ]]; do value=1 case "$1" in (-a|--archive) apt_archive="$2" value=2 ;; (-c|--cache) apt_p2p_cache="$2" value=2 ;; (-e|--execute) execute=1 ;; (-h|--help) usage ;; (-n|--no-execute) execute=0 ;; (-v|--version) version ;; esac shift $value done [[ -z $execute ]] && usage unset value set -e for directory in "$apt_p2p_cache" "$apt_archive"; do if [[ ! -r "$directory" ]] || [[ ! -x "$directory" ]]; then echo "$program: $directory: Permission denied" 1>&2 exit 1 fi done if [[ $execute -eq 1 ]]; then echo 'Removing files:' else echo 'Would remove files:' fi find "$apt_p2p_cache" -name '*.deb' | ( freed=0 while read deb; do _deb="${deb##*/}" _deb="${_deb//%7e/~}" if [[ ! -f "$apt_archive/$_deb" ]]; then if dpkg-deb -W $deb >/dev/null 2>&1; then _deb=`dpkg-deb -W --showformat='${Package}_${Version}_${Architecture}.deb' $deb` fi if [[ ! -f "$apt_archive/${_deb//:/%3a}" ]]; then # XXX: '|| true' because bash believes ((freed += 0)) is bad ((freed += `du -B 1 $deb | cut -f 1`)) || true echo " $_deb" [[ $execute -eq 1 ]] && rm -f "$deb" fi fi done if [[ $execute -eq 1 ]]; then [[ $freed != 0 ]] && invoke-rc.d apt-p2p restart echo -n 'Freed' else echo -n 'Would free' fi echo " `bc <<-EOF freed=$freed scale=1 if (freed >= 1024 ^ 3) print freed / 1024 ^ 3, "G" else if (freed >= 1024 ^ 2) print freed / 1024 ^ 2, "M" else if (freed >= 1024) print freed / 1024, "K" else freed EOF`B of disk space" ) # Clean up the Apt-P2P cache