#!/bin/bash

#
### Небольшой скрипт для поиска и отстройки пакетов из AUR
#   для более требовательных юзать - yaourt
#
# Version: 20090728.1
#
# «THE BEER-WARE LICENSE» (Revision 42):
# hatred@inbox.ru wrote this file. As long as you retain
# this notice you can do whatever you want with this stuff.
# If we meet some day, and you think this stuff is worth it,
# you can buy me a beer in return. Alexander 'hatred' Drozdoff 
#

pkgname=""

die() {
	echo $*
	exit 1
}

use() {
cat << _EOF_
  Small script for getting and build ArchLinux pkg from AUR
  Use: $(basename $0) [action] [pkgname]
   Where action is:
      get  <pkgname>   - download only.
      unpack <pkgname> - unpack archive
      make <pkgname>   - make package, unpack, if not unpacked,
                         download, if not downloaded.
      clean <pkgname>  - remove downloaded package and unpacked dir.
      build <pkgname>  - combine clean, get, unpack, make. Default action.
      help             - this screen.
  
  If you call script as '$(basename $0) <pkgname>' action 'build' is assumed.
  You can set system variable 'EDITPKG' to 1 for PKGBUILD edit ability. 
_EOF_
}

get() {
	echo "Downloading $pkgname.tar.gz"
	wget -q http://aur.archlinux.org/packages/$pkgname/$pkgname.tar.gz || die "Failed to fetch $1.tar.gz"
}

unpack() {
	if [ -f $pkgname.tar.gz ]; then
		if [ -d $pkgname ]; then
			if [ -z "$FORCE" ]; then
				read -p "Delete unpacked directoy? [Y/n] " yn
				if [ x"$yn" = x"" -o x"$yn" = x"Y" -o x"$yn" = x"y" ]; then
					rm -rf $pkgname
				fi
			else
				rm -rf $pkgname
			fi
		fi

		tar zxf $pkgname.tar.gz || die "Extraction failed"
		
		if [ ! -z "$EDITPKG" ]; then
			vim $pkgname/PKGBUILD
		fi
	else
		die "Can't found file '$pkgname.tar.gz'. Is it downloaded?"
	fi
}

make() {
	if [ ! -d "$pkgname" ]; then
		if [ ! -f "$pkgname.tar.gz" ]; then
			get
		fi
		unpack
	fi

	cd $pkgname || die "Failed to cwd"
	makepkg
}

clean() {
	rm -rf $pkgname
	rm -rf $pkgname.tar.gz
}

if [ "$1" == "" ]; then
	use
	exit 1
fi

#[ -d $pkgname  ] && die "Directory '$pkgname' already exists"
#[ -f $pkgname  ] && die "File '$pkgname' already exists"

action=$1
pkgname=$2
case $action in
	get|unpack|make|clean)
		$action
	;;
	help)
		use
		exit 0
	;;
	*)
		pkgname=$1
		clean
		get
		unpack
		make
	;;
esac
