#!/usr/bin/env bash
#
#   pacman-optimize
#   Generated from pacman-optimize.sh.in; do not edit by hand.
#
#   Copyright (c) 2006-2016 Pacman Development Team <pacman-dev@archlinux.org>
#   Copyright (c) 2002-2006 by Judd Vinet <jvinet@zeroflux.org>
#
#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation; either version 2 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

# gettext initialization
export TEXTDOMAIN='pacman-scripts'
export TEXTDOMAINDIR='/usr/share/locale'

USE_COLOR='y'

declare -r myver='5.0.1'

eval $(awk '/DBPath/ {print $1$2$3}' /etc/pacman.conf)
dbroot="${DBPath:-/var/lib/pacman/}"

plain() {
	(( QUIET )) && return
	local mesg=$1; shift
	printf "${BOLD}    ${mesg}${ALL_OFF}\n" "$@" >&1
}

msg() {
	(( QUIET )) && return
	local mesg=$1; shift
	printf "${GREEN}==>${ALL_OFF}${BOLD} ${mesg}${ALL_OFF}\n" "$@" >&1
}

msg2() {
	(( QUIET )) && return
	local mesg=$1; shift
	printf "${BLUE}  ->${ALL_OFF}${BOLD} ${mesg}${ALL_OFF}\n" "$@" >&1
}

ask() {
	local mesg=$1; shift
	printf "${BLUE}::${ALL_OFF}${BOLD} ${mesg}${ALL_OFF}" "$@" >&1
}

warning() {
	local mesg=$1; shift
	printf "${YELLOW}==> $(gettext "WARNING:")${ALL_OFF}${BOLD} ${mesg}${ALL_OFF}\n" "$@" >&2
}

error() {
	local mesg=$1; shift
	printf "${RED}==> $(gettext "ERROR:")${ALL_OFF}${BOLD} ${mesg}${ALL_OFF}\n" "$@" >&2
}


if [[ -n "$MSYSTEM" ]]; then
  readonly -a UTILS_NAME=('bsdtar'
                          'bzip2'
                          'bzr'
                          'cat'
                          'ccache'
                          'distcc'
                          'git'
                          'gpg'
                          'gzip'
                          'hg'
                          'lzip'
                          'lzop'
                          'openssl'
                          'svn'
                          'tput'
                          'uncompress'
                          'upx'
                          'xargs'
                          'xz'
                         )

  for wrapper in ${UTILS_NAME[@]}; do
    eval "
    ${wrapper}"'() {
      local UTILS_PATH="/usr/bin/"
      if ! type -p ${UTILS_PATH}${FUNCNAME[0]} >/dev/null; then
        error "$(gettext "Cannot find the %s binary required for makepkg.")" "${UTILS_PATH}${FUNCNAME[0]}"
        exit 1
      fi
      ${UTILS_PATH}${FUNCNAME[0]} "$@"
    }'
  done
fi


usage() {
	printf "pacman-optimize (pacman) %s\n\n" "$myver"
	printf -- "$(gettext "Usage: %s [--nocolor] [pacman_db_root]")\n\n" "$0"
	printf -- "$(gettext "\
pacman-optimize is a little hack that should improve the performance\n\
of pacman when reading/writing to its filesystem-based database.\n\n")"
	printf -- "$(gettext "\
Because pacman uses many small files to keep track of packages,\n\
there is a tendency for these files to become fragmented over time.\n\
This script attempts to relocate these small files into one\n\
continuous location on your hard drive. The result is that the hard\n\
drive should be able to read them faster, since the hard drive head\n\
does not have to move around the disk as much.\n")"
}

version() {
	printf "pacman-optimize (pacman) %s\n" "$myver"
	printf -- "$(gettext "\
Copyright (c) 2006-2016 Pacman Development Team <pacman-dev@archlinux.org>.\n\
Copyright (C) 2002-2006 Judd Vinet <jvinet@zeroflux.org>.\n\n\
This is free software; see the source for copying conditions.\n\
There is NO WARRANTY, to the extent permitted by law.\n")"
}

die() {
	error "$@"
	exit 1
}

die_r() {
	rm -f "$lockfile"
	die "$@"
}

# PROGRAM START

# determine whether we have gettext; make it a no-op if we do not
if ! type -p gettext >/dev/null; then
	gettext() {
		printf "%s\n" "$@"
	}
else
	gettext() {
		/usr/bin/gettext "$@"
	}
fi

if [[ $1 = "-h" || $1 = "--help" ]]; then
	usage
	exit 0
fi

if [[ $1 = "-V" || $1 = "--version" ]]; then
	version
	exit 0
fi

if [[ $1 = "--nocolor" ]]; then
	USE_COLOR='n'
	shift
fi

# check if messages are to be printed using color
unset ALL_OFF BOLD BLUE GREEN RED YELLOW
if [[ -t 2 && ! $USE_COLOR = "n" ]]; then
	# prefer terminal safe colored and bold text when tput is supported
	if tput setaf 0 &>/dev/null; then
		ALL_OFF="$(tput sgr0)"
		BOLD="$(tput bold)"
		BLUE="${BOLD}$(tput setaf 4)"
		GREEN="${BOLD}$(tput setaf 2)"
		RED="${BOLD}$(tput setaf 1)"
		YELLOW="${BOLD}$(tput setaf 3)"
	else
		ALL_OFF="\e[1;0m"
		BOLD="\e[1;1m"
		BLUE="${BOLD}\e[1;34m"
		GREEN="${BOLD}\e[1;32m"
		RED="${BOLD}\e[1;31m"
		YELLOW="${BOLD}\e[1;33m"
	fi
fi
readonly ALL_OFF BOLD BLUE GREEN RED YELLOW


if [[ -n $1 ]]; then
	dbroot="$1"
fi

if ! type -p openssl >/dev/null; then
	die "$(gettext "Cannot find the %s binary required for verifying integrity.")" "openssl"
fi

if [[ ! -d $dbroot || ! -d $dbroot/local ]]; then
	die "$(gettext "%s does not exist or is not a directory.")" "$dbroot"
fi

if [[ ! -w $dbroot ]]; then
	die "$(gettext "You must have correct permissions to optimize the database.")"
fi

# strip any trailing slash from our dbroot
dbroot="${dbroot%/}"
lockfile="${dbroot}/db.lck"
localdb="${dbroot}/local"

# make sure pacman isn't running
if [[ -f $lockfile ]]; then
	die "$(gettext "Pacman lock file was found. Cannot run while pacman is running.")"
fi
# do not let pacman run while we do this
touch "$lockfile"

workdir=$(mktemp -d "${TMPDIR:-/tmp}/pacman-optimize.XXXXXXXXXX") ||
	die_r "$(gettext "Cannot create temporary directory for database building.")\n" >&2

# step 1: sum the old db
msg "$(gettext "MD5sum'ing the old database...")"
(cd "$localdb" && find . -type f -print0 | \
	xargs -0 openssl dgst -md5 | sort > "$workdir/pacsums.old")

# step 2: tar it up
msg "$(gettext "Tar'ing up %s...")" "$localdb"
bsdtar -czf "$workdir/pacman-db.tar.gz" -C "$localdb" ./
if (( $? )); then
	rm -rf "$workdir"
	die_r "$(gettext "Tar'ing up %s failed.")" "$localdb"
fi

# step 3: make and sum the new db side-by-side with the old
msg "$(gettext "Making and MD5sum'ing the new database...")"
mkdir "$localdb.new"
bsdtar -xpf "$workdir/pacman-db.tar.gz" -C "$localdb.new"
if (( $? )); then
	rm -rf "$workdir"
	die_r "$(gettext "Untar'ing %s failed.")" "$localdb"
fi
# immediate sync following extraction should get it written continuously on HDD
msg "$(gettext "Syncing database to disk...")"
sync
(cd "$localdb.new" && find . -type f -print0 | \
	xargs -0 openssl dgst -md5 | sort > "$workdir/pacsums.new")

# step 4: compare the sums
msg "$(gettext "Checking integrity...")"
read -ra old_dgst < <(openssl dgst -md5 < "$workdir/pacsums.old")
read -ra new_dgst < <(openssl dgst -md5 < "$workdir/pacsums.new")
if [[ ${old_dgst[@]:(-1)} != ${new_dgst[@]:(-1)} ]]; then
	# failed
	# leave our pacman-optimize tmpdir for checking to see what doesn't match up
	rm -rf "$localdb.new"
	die_r "$(gettext "Integrity check FAILED, reverting to old database.")"
fi

# step 5: shuffle the newly extracted DB into the proper location
msg "$(gettext "Rotating database into place...")"

fail=0
mv "$localdb" "$localdb.old" || fail=1
mv "$localdb.new" "$localdb" || fail=1
chmod $(stat -c '%a' "$localdb.old") "$localdb" || fail=1
chown $(stat -c '%u:%g' "$localdb.old") "$localdb" || fail=1
if (( fail )); then
	# failure with our directory shuffle
	die_r "$(gettext "New database substitution failed. Check for %s, %s, and %s directories.")" "$localdb" "$localdb.old" "$localdb.new"
fi
rm -rf "$localdb.old"

# remove the lock file and our working directory with sums and tarfile
rm -f "$lockfile"
rm -rf "$workdir"

echo
msg "$(gettext "Finished. Your pacman database has been optimized.")"
echo

exit 0

# vim: set noet:
