# Maintainer: George Rawlinson <george@rawlinson.net.nz>

pkgname=rutorrent
_pkgname=ruTorrent
pkgver=3.10
# git submodule within source
# commit ID obtained from $pkgver tree
_darkbetter_commitid="c1f7817f3cc9930c7ec7a4d50b1c131670ec888e"
pkgrel=1
pkgdesc="Yet another web front-end for rTorrent"
arch=('any')
url='https://github.com/Novik/ruTorrent'
license=('GPL')
depends=(php-fpm php-geoip curl gzip coreutils)
makedepends=(perl git)
optdepends=()
conflicts=()
source=(
  "$pkgname-$pkgver.tar.gz::$url/archive/v$pkgver.tar.gz"
  "DarkBetter-$_darkbetter_commitid.tar.gz::https://github.com/chocolatkey/DarkBetter/archive/$_darkbetter_commitid.tar.gz"
  "tmpfiles.conf"
)
b2sums=('58ce8673bbb5f25509e4b81bc41512d42221dd36a42aa856b2956c6cc8ad5096c675ef941f45592246b4d04432269146f61544fd7ee1c0f50fa6a08edad93914'
        '8c490225c478b43738611c305f539bfe2bc1053247a0f4a2b304a5e55a4f8f5be3f490cddbbdb3bef1bb672e1824cd09a6c38dcd021fad1b6945a179430e1f7a'
        'f762fe34e415632f4a458f83ab305a7c5fe231c04ed3cce7b3a7ab99e00aa4a767bab8212edcff80b954d974cf347919b36052dcea5caf0504fb79b745456349')
backup=( 
	etc/rutorrent/config.php
	etc/rutorrent/plugins.ini
	etc/rutorrent/access.ini
)
options=(emptydirs !strip)

prepare() {
	cd "$_pkgname-$pkgver"

	# move config & log location
	sed -i \
		-e 's:../share:/var/lib/rutorrent:' \
		-e 's:tmp/errors.log:var/log/rutorrent.log:' \
		conf/config.php

	# move config/settings to /var/lib/rutorrent
	rm -rf share
	
	# replace with version pinned at git tag rather than latest
	rm -rf plugins/theme/themes/DarkBetter

	# delete git files
	find . -type f -name ".git*" -delete

	# delete POSIX-incompatible files
	cd plugins/tracklabels/labels
	find . -print0 | perl -MFile::Path=remove_tree -n0e 'chomp; remove_tree($_, {verbose=>1}) if /[[:^ascii:][:cntrl:]]/'
}

package() {
	cd "$_pkgname-$pkgver"

	# create directories
	install -d "$pkgdir/usr/share/$pkgname/conf"
	install -d "$pkgdir/etc/$pkgname"

	# copy files over
	cp -r . "$pkgdir/usr/share/$pkgname"
	cp -r "$srcdir/DarkBetter-$_darkbetter_commitid" \
		"$pkgdir/usr/share/$pkgname/plugins/theme/themes/DarkBetter"

	# link config files to /etc/$pkgname
	for conf in config.php plugins.ini access.ini; do
		mv "conf/$conf" "$pkgdir/etc/$pkgname"
		ln -sf "/etc/$pkgname/$conf" "$pkgdir/usr/share/$pkgname/conf/$conf"
	done

	# license & documentation
	install -Dm644 -t "$pkgdir/usr/share/licenses/$pkgname" LICENSE.md
	install -Dm644 -t "$pkgdir/usr/share/doc/$pkgname" README.md htaccess-example

	# remove unnecessary files
	rm "$pkgdir/usr/share/$pkgname/"{LICENSE.md,README.md,htaccess-example}

	# systemd integration
	install -Dm644 "$srcdir/tmpfiles.conf" "$pkgdir/usr/lib/tmpfiles.d/$pkgname.conf"

	# change ownership
	chown -R http:http "$pkgdir/usr/share/$pkgname"
}