#!/bin/sh
# 2005-2009 (c) Etersoft www.etersoft.ru
# Author: Vitaly Lipatov <lav@etersoft.ru>
# Public domain
#
# CS -- cleanup spec (like cleanup_spec command)
# Параметры:
# - название спек-файла

# load common functions, compatible with local and installed script
. `dirname $0`/../share/eterbuild/functions/common
load_mod rpm repl spec

set_gear_host

dummy_spec()
{
grep "^Name" $1
grep "^Version" $1
grep "^Release" $1
grep "^Packager" $1
cat <<EOF
Summary: dummy
License: dummy
Group: dummy
%description
EOF
}

# Get replacement rule for some package in $1 to ALT
toalt_pkgrepl()
{
	local i
	WARULES="s/^ //g 
		s/ \$//g 
		s/ |/|/g 
		s/| /|/g"
	# FIXME: what rules we need really?
	for i in $PKGREPLBASE/pkgrepl.fedora* $PKGREPLBASE/pkgrepl.rpm $PKGREPLBASE/pkgrepl.mdv* ; do
		#echo $i - $1
		test -r "$i" || continue
		REPLRULE=`grep -v "^#" "$i" 2>/dev/null | grep -- "$1\$" | sed -e "$WARULES" | sed -e "s/^\(.*\)|\(.*\)\$/\2|\1/g" | tail -n1`
		# For broken rule
		echo $REPLRULE | grep "^|" >/dev/null && REPLRULE=""
		echo $REPLRULE | grep "|\$" >/dev/null && REPLRULE=""
		if [ -n "$REPLRULE" ] ; then
			REPLRULE1=`echo $REPLRULE | cut -d"|" -f1 | sed -e "s|\+|\\\\\+|g"`
			REPLRULE2=`echo $REPLRULE | cut -d"|" -f2 | sed -e "s|\+|\\\\\+|g"`
			# really if they are identically both, there is no replacement
			[ "$REPLRULE1" = "$REPLRULE2" ] && return 1
			return 0
		else
			REPLRULE1=
			REPLRULE2=
		fi
	done
	return 1
}

# TODO: down handle spaces correctly
# Get replacement rule for some group in $1 to ALT
toalt_grprepl()
{
	local i REPLRULE WARULES
	WARULES="s/^ //g 
		s/ \$//g 
		s/ |/|/g 
		s/| /|/g"
	GRPREPLBASE=$PKGREPLBASE/../grprepl
	for i in $GRPREPLBASE/grprepl.fedora $GRPREPLBASE/grprepl.rpm $GRPREPLBASE/grprepl.* ; do
		test -r "$i" || continue
		# altbug #24724 (FIXME: check again for cyclic)
		rhas "$i" "grprepl.alt" && continue
		REPLRULE=`grep -v "^#" "$i" 2>/dev/null | grep -- "$1\$" | sed -e "$WARULES" | sed -e "s/^\(.*\)|\(.*\)\$/\2|\1/g" | head -n1`
		# For broken rule
		echo $REPLRULE | grep "^|" >/dev/null && REPLRULE=""
		echo $REPLRULE | grep "|\$" >/dev/null && REPLRULE=""
		if [ -n "$REPLRULE" ] ; then
			GRPREPLRULE1=`echo $REPLRULE | cut -d"|" -f1 | sed -e "s|\+|\\\\\+|g"`
			GRPREPLRULE2=`echo $REPLRULE | cut -d"|" -f2 | sed -e "s|\+|\\\\\+|g"`
			return 0
		else
			GRPREPLRULE1=
			GRPREPLRULE2=
		fi
	done
	return 1
}

do_repls()
{
	local i=$1
	local SPEC=$2
	# TODO use perl -pe
	echog "fix build requires..."
	ALLREPLRULES=""
	for n in `print_buildreq $i` ; do
		toalt_pkgrepl $n || continue
		ALLREPLRULES="$ALLREPLRULES
			s|(.*Req.*)$REPLRULE1|\1$REPLRULE2|g"
		[ -n "$VERBOSE" ] && echo "Replace '$REPLRULE1' with '$REPLRULE2'"
	done

	echog "fix package requires..."
	for n in `print_pkgreq $i` ; do
		toalt_pkgrepl $n || continue
		ALLREPLRULES="$ALLREPLRULES
			s|(.*Req.*)$REPLRULE1|\1$REPLRULE2|g"
		[ -n "$VERBOSE" ] && echo "Replace '$REPLRULE1' with '$REPLRULE2'"
	done

	# commented out: do incorrect replacement for clean ALT packages
	if false ; then
	echog "fix groups..."
	for n in `print_grpreq $i` ; do
		toalt_grprepl $n || continue
		ALLREPLRULES="$ALLREPLRULES
			s|(^Group.*)$GRPREPLRULE1|\1$GRPREPLRULE2|g"
		[ -n "$VERBOSE" ] && echo "Replace '$GRPREPLRULE1' with '$GRPREPLRULE2'"
	done
	fi

	# Replace package names in source spec
	sed -r -e "$ALLREPLRULES" <$i >$SPEC || { warning "Error with replacement" ; cat $i >$SPEC ; }

	echo
	echo "Total used replacement rules: $ALLREPLRULES"
}



Usage="Usage: rpmcs [--skip-reqs] [specfile]
spec file can be autodetected from git repo"
mygetopts()
{
Descr="rpmcs (Cleanup Spec) - cleanup spec (like cleanup_spec command)"

phelp()
{
# TODO: improve description
	echog "$Descr"
	echog "$Usage"
	echog " specfile - spec file (copy will be saved as specfile~)"
	echog " --skip-reqs  do not replace requires"
	exit 0
}

if [ "$1" = "-h" ] || [ "$1" = "--help" ] ; then
	phelp
fi

# pass other options to RPM:
LISTRPMARGS=$@
}

if [ "$1" = "--skip-reqs" ] ; then
	SKIPREQS=1
	shift
fi

# If run without params, try autodetect spec
if [ -z "$1" ] ; then
	LISTNAMES=$(get_gear_spec)
	[ -n "$LISTNAMES" ] && echo "Using autodetected spec $LISTNAMES..."
else
	parse_cmd_pre "$@"
	mygetopts $LISTARGS
fi

for SPEC in $LISTNAMES
do
	if [ -z ${SPEC/*rpm/} ] ; then
		fatal "'$SPEC' is not not spec file"
	fi

	# Make backup copy
	cp -f $SPEC ${SPEC}~ || fatal "Cannot find spec file '$SPEC'"

	# Add group
	if ! grep "^Group" $SPEC ; then
		PACKAGT="Group: Unknown"
		cat $SPEC | awk 'BEGIN{desk=0}{if(/^U[rR][lL]/&&desk==0){printf("%s\n", text);desk++};print}' text="$PACKAGT" >$SPEC.tmp && mv -f $SPEC.tmp $SPEC
	fi

	# Prepare for fix only before changelog part
	i=$SPEC.tmpspecbeforechangelog
	separate_changelog $SPEC $i $SPEC.tmpspecchangelog

	# Unneeded on ALT
	subst "s|^Prefix:.*$||" $i
	subst "s|^BuildRoot:.*$||i" $i
	subst "s|%mkrel||g" $i
	
	# Unused on ALT
	subst "s|^Suggests:|#Suggests:|" $i
	subst "s|^Recommends:|#Recommends:|g" $i



# use in cases
#	subst "s|%mdkversion||g" $i

	# TODO: drop it
	# If it was PLD spec
	if grep "^%define date" $i ; then
		# with dummy spec we can't have any parsing problems
		if false ; then
			dummy_spec $i >$i.dummy
			subst "s|^%changelog.*|`stamp_spec $i.dummy`|" $i
			rm -f $i.dummy
			subst "s|^%define date.*|%changelog|" $i
			subst "s|* %{date} PLD Team\(.*\)|- initial build for ALT Sisyphus (spec from PLD Team)|" $i
		else
			echo "PLD spec..."
			awk '{if ( ! /^%define date/){print}else{exit}}' $i > $i.tmp && mv -f $i.tmp $i
			add_changelog $i -e "- initial build for ALT Sisyphus (spec from PLD)"
		fi
	fi

	echog "cleanup_spec for $i..."
	cleanup_spec $i

	subst "s|^%configure2_5x|%configure|g" $i

	# convert from PLD's cases
	subst "s|%if %{with \(.*\)}|%if_with \1|g" $i
	subst "s|%if %{without \(.*\)}|%if_without \1|g" $i
	# replaces Fedora's with and without too
	subst "s|^%bcond_with|%def_with|g" $i
	subst "s|^%bcond_without|%def_without|g" $i
	#subst "s|%{?with_\(.*\):|%{subst_with

	echog "fix name and release..."
	build_rpms_name "$i"

	
	echog -n "fix obsoleted constructions..."
	subst "s|Source0:|Source:|" $i
	subst "s|Patch0:|Patch:|" $i

	set_specdir $i
	if ! is_gear $SPECDIR && [ -n "$RENAME_SOURCE_TARBALL" ] ; then
		# Use tar.bz2 for tarball if not git case.
		subst "s|\(Source:.*\).tar.gz|\1.tar.bz2|" $i
		subst "s|\(Source:.*\).tgz|\1.tar.bz2|" $i
	fi
	

	subst "s|\(%post.*-p *\)/sbin/ldconfig|\1%post_ldconfig|g" $i
	subst "s|\(%postun.*-p *\)/sbin/ldconfig|\1%postun_ldconfig|g" $i


	subst "s|^%_post_service.*||g" $i
	subst "s|^%_preun_service.*||g" $i
	
	subst "s|\$RPM_BUILD_ROOT/%|%buildroot%|g" $i
	subst "s|\$RPM_BUILD_ROOT|%buildroot|g" $i
	#subst "s|%buildrootetc|%buildroot/etc|g" $i

	# Fix groups to ALT's
	subst "s|Group: *Libraries|Group: System/Libraries|g" $i

	# It is not recommended to use macroses for commands (__subst is unique in this)
	subst  "s|%__install |install |g 
		s|%__cp |cp |g 
		s|%__rm -f |rm -f |g 
		s|%__mv |mv |g 
		s|%__mkdir_p|mkdir -p|g 
		s|%__mkdir |mkdir |g 
		s|%__make |make |g 
		s|%__awk |gawk |g 
		s|%__bzip2 |bzip2 |g 
		s|%__cat |cat |g 
		s|%__chgrp |chgrp |g 
		s|%__chmod |chmod |g 
		s|%__chown |chown |g 
		s|%__cpio |cpio |g 
		s|%__file |file |g 
		s|%__gpg |gpg |g 
		s|%__grep |grep |g 
		s|%__gzip |gzip |g 
		s|%__id |id |g 
		s|%__install |install |g 
		s|%__install_info |install-info |g 
		s|%__ln_s |ln -s |g 
		s|%__patch |patch |g 
		s|%__perl |perl |g 
		s|%__pgp |pgp |g 
		s|%__python |python |g 
		s|%__rm |rm |g 
		s|%__rsh |rsh |g 
		s|%__sed |sed |g 
		s|%__ssh |ssh |g 
		s|%__tar |tar |g 
		s|%__unzip |unzip |g 
		s|%__ar |ar |g 
		s|%__as |as |g 
		s|%__cc |gcc |g 
		s|%__cpp |gcc -E |g 
		s|%__cxx |g++ |g 
		s|%__ld |ld |g 
		s|%__nm |nm |g 
		s|%__objcopy |objcopy |g 
		s|%__objdump |objdump |g 
		s|%__ranlib |ranlib |g 
		s|%__tar |tar |g" $i

# CHECK ME:
#		s|%__strip|strip|g 
#		s|%__libtoolize|libtoolize|g 
#		s|%__aclocal|aclocal|g 
#		s|%__autoheader|autoheader|g 
#		s|%__automake|automake|g 
#		s|%__autoconf|autoconf|g 


	subst  "s|%__make *install|%make_install install|g
		s|^make *install|%make_install install|g
		s|^make %{?_smp_mflags}|%make_build|g
		s|^make %{?_smp_flags}|%make_build|g
		s|%make_install *install *DESTDIR=%buildroot|%makeinstall_std|g
		s|%make_install *DESTDIR=%buildroot *install\$|%makeinstall_std|g
		s|%make_install *DESTDIR=%buildroot *install |%makeinstall_std|g
		s|^make *DESTDIR=%buildroot *install\$|%makeinstall_std|g
		s|^make *DESTDIR=%buildroot *install |%makeinstall_std|g
		s|^make DESTDIR=%buildroot INSTALL='install -p' install|%makeinstall_std|g" $i

#	subst  "s|/etc/|%_sysconfdir/|g
#		s|%_sysconfdir/rc.d/init.d|%_initdir/|g
#		s|%_sysconfdir/rc.d/init.d/|%_initrddir/|g
#		s|%_sysconfdir/init.d/|%_initrddir/|g"

	subst	"s|/etc/rc.d/init.d/|%_initrddir/|g" $i

	subst	"s|%_sysconfdir/X11/fontpath.d|%_fontpathdir|g" $i

	subst  "s|%_libdir/mono/gac|%_monogacdir|g
		s|%_libdir/mono|%_monodir|g" $i

	subst  "s|%prefix/lib/|%_libdir/|g
		s|%prefix/lib64/|%_libdir/|g
		s|%prefix/%_lib|%_libdir|g
		s|%prefix/libexec|%_libexecdir|g
		s|/usr/%_lib|%_libdir|g
		s|%prefix/include|%_includedir|g
		s|/usr/include|%_includedir|g
		s|/usr/src|%_usrsrc|g
		s|%prefix/share|%_datadir|g" $i

	subst "s|Requires(post): /sbin/install-info|Requires(post): %install_info|g" $i
	subst "s|Requires(preun): /sbin/install-info|Requires(preun): %uninstall_info|g" $i

	# also clean_scrollkeeper exists
	#subst "s|^scrollkeeper-update|%update_scrollkeeper|g" $i

	# FIXME: only in rpm-build-compat
	#subst "s|^%_datadir/aclocal/|%_aclocaldir/|g" $i
	#subst "s|^%_datadir/gtk-doc/html/|%_gtkdocdir/|g" $i

	# TODO: not in expressions
	subst  "s|/usr/sbin/|%_sbindir/|g
		s|/usr/bin/|%_bindir/|g
		s|%prefix/bin/|%_bindir/|g
		s|/usr/lib/|%_libexecdir/|g
		s|/usr/share/|%_datadir/|g
		s|%_datadir/games|%_gamesdatadir|g" $i

	subst "s|%pear_phpdir|%pear_dir|g" $i
	# changes for rpm-build-pear 0.3
	# FIXME: remove pear_install replacing in future
	subst  "s|%pear_install\$|%register_pear_module|g
		s|%pear_uninstall|%unregister_pear_module|g
		s|%pear_prepare_module|%pear_build|g
		s|%pear_install_module|%pear_install_std|g" $i

	# subst normalize	
	subst  "s|^sed -i -e |%__subst |g
		s|^subst |%__subst |g
		s|^sed -i |%__subst |g
		s|perl -pi -e *|%__subst |g" $i

	subst "s|^python |%__python |g
		s|%py_sitescriptdir|%python_sitelibdir|g
		s|%py_puresitedir|%python_sitelibdir|g
		s|%python_version|%__python_version|g
		s|%__python2 |%__python |g
		s|%python2_version|%__python_version|g
		s|%python_sitelib/|%python_sitelibdir/|g
		s|%python2_sitelib/|%python_sitelibdir/|g
		s|%python3_sitelib/|%python3_sitelibdir/|g
		s|%_libdir/python2.[67]/site-packages/|%python_sitelibdir/|g
		s|%py_sitedir/|%python_sitelibdir/|g
		s|%python_sitearch|%python_sitelibdir|g
		s|%python2_sitearch|%python_sitelibdir|g
		s|\(%pyrequires_eq.*\)|#\1|g" $i

	subst "s|ruby setup.rb config|%ruby_config|g
		   s|ruby setup.rb setup|%ruby_setup|g" $i

	subst "s|^%__python setup.py build|%python_build|g" $i
	subst 's|^CFLAGS="$RPM_OPT_FLAGS" python setup.py build|%python_build|g' $i
	subst 's|^CFLAGS="%optflags" python setup.py build|%python_build|g' $i
	subst "s|^%py2_build |%python_build |g" $i
	subst "s|^%py2_install |%python_install |g" $i
	subst "s|^%py3_build |%python3_build |g" $i
	subst "s|^%py3_install |%python3_install |g" $i
	subst "s|^%py2_build$|%python_build|g" $i
	subst "s|^%py2_install$|%python_install|g" $i
	subst "s|^%py3_build$|%python3_build|g" $i
	subst "s|^%py3_install$|%python3_install|g" $i
	subst "s|^%__python setup.py install --root.%buildroot|%python_install|g" $i
	subst "s|^%__python setup.py install --skip-build --root[ =]%buildroot|%python_install|g" $i
	subst "s|^%__python3 setup.py install --skip-build --root[ =]%buildroot|%python3_install|g" $i
	subst "s|^%__python setup.py install -O1 --skip-build --root %buildroot|%python_install|g" $i
	subst "s|^%__python setup.py install -O2 --root %buildroot|%python_install|g" $i
	subst "s|^%__python setup.py install --optimize --root %buildroot|%python_install|g" $i
	
	subst "s|%_datadir/man/|%_mandir/|g" $i
	subst "s|%_mandir/man\([0-9]\)|%_man\1dir|g" $i
	subst "s|%_libdir/pkgconfig|%_pkgconfigdir|g" $i
	#subst "s|%_datadir/pkgconfig|%_noarchpkgconfigdir|g" $i
	subst "s|%_datadir/pixmaps|%_pixmapsdir|g" $i
	subst "s|%_datadir/applications|%_desktopdir|g" $i

	subst "s|%update_desktop_database|%update_desktopdb|g" $i
	subst "s|%clean_desktop_database|%clean_desktopdb|g" $i

	subst "s|%gconf_schema_install \(.*\)\.schemas|%gconf2_install \1|g" $i
	subst "s|%_browserpluginsdir|%browser_plugins_path|g" $i

	subst  "s|%_iconsdir/hicolor/48x48/apps|%_liconsdir|g
		s|%_iconsdir/hicolor/16x16/apps|%_miconsdir|g
		s|%_iconsdir/hicolor/32x32/apps|%_niconsdir|g
		s|%_iconsdir/mini|%_miconsdir|g
		s|%_iconsdir/large|%_liconsdir|g
		s|%_datadir/icons|%_iconsdir|g" $i

	# browser/mozilla extensions
	subst  "s|%_libdir/mozilla/extensions|%mozilla_arch_extdir|g
		s|%_datadir/mozilla/extensions/any|%mozilla_any_extdir|g
		s|%_datadir/mozilla/extensions|%mozilla_noarch_extdir|g
		s|%_libdir/browser-plugins|%browser_plugins_path|g" $i

	# remove MDK compatibility macroses
	subst "s|%perl_vendorlib|%perl_vendor_privlib|g
		   s|%perl_vendorarch|%perl_vendor_archlib|g" $i

	# TODO for cleanup_spec:
	subst "s|%_datadir/doc$|%_docdir|g
		s|%_datadir/doc/|%_docdir/|g
		s|%_datadir/omf|%_omfdir|g
		s|%_defaultdocdir|%_docdir|g
		s|%_var/log|%_logdir|g
		s|%_localstatedir/log|%_logdir|g
		s|%_localstatedir/cache|%_cachedir|g
		s|%_localstatedir/lib|%_sharedstatedir|g
		# See https://bugzilla.altlinux.org/show_bug.cgi?id=10382
		#s|%_var/lib|%_localstatedir|g
		s|/var/lock/subsys|%_locksubsysdir|g
		s|%_sysconfdir/tmpfiles.d|%_tmpfilesdir|g
		s|%_localstatedir/run|%_runtimedir|g
		s|/var/run|%_runtimedir|g
		s|%_sysconfdir/logrotate.d|%_logrotatedir|g
		s|%_sysconfdir/udev/rules.d|%_udevrulesdir|g
		s|%__autoreconf|%autoreconf|g" $i

	if grep -q rpm-build-intro $i || grep -q rpm-macros-intro-conflicts $i ; then
		subst "s|%_sysconfdir/sysconfig|%_sysconfigdir|g
		s|||g" $i
	fi

	subst "s|%rpmcflags|%optflags|g" $i

	# %license means License field in ALT rpm
	subst "s|^%license |%doc |g" $i

	subst "s|^%autosetup|%setup|g" $i

	# drop useless construction
	subst "s|%setup -q|%setup|g" $i
	subst "s|^%clean$||g" $i
	subst "s|^%debug_package$||g" $i
	subst "s|^rm -rf %buildroot$||g" $i
	subst "s|^%defattr(-,root,root)||g" $i
	subst "s|^%defattr(644,root,root,755)||g" $i
	#subst "s|^%attr(.*)\(.*\)$|\1|g" $i
	subst "s|^ *%|%|g" $i

	# If non alt release, set initial alt release
	if ! rhas "$RELEASE" "^alt" && ! rhas "$RELEASE" "^$(get_default_txtrelease)" ; then
		reset_release $i
	fi

	# For case if name was macros
	test -n "$BASENAME" && set_var $i Name $BASENAME
	
	# For case if version was macros
	# set_version is major define safe
	test -n "$VERSION" && set_version $i $VERSION

	# Add packager
	if ! grep "^Packager" $i ; then
		PACKAGT="Packager: $OWNERMAIL"
		rhas "$OWNERMAIL" "packager" && fatal "Packager $OWNERMAIL is not defined correctly in ~/.rpmmacros"
		cat $i | awk 'BEGIN{desk=0}{if(/^Source/&&desk==0){printf("%s\n\n", text);desk++};print}' text="$PACKAGT" >$i.tmp && mv -f $i.tmp $i
	fi

	echog "DONE"

	if [ -z "$SKIPREQS" ] ; then
		do_repls $i $SPEC
	else
		cat $i > $SPEC
	fi


	# Restore changelog
	cat $SPEC.tmpspecchangelog >>$SPEC
	rm -f $i $SPEC.tmpspecchangelog
	
	# if there is no altlinux in changelog yet
	if ! grep -v "Packager" $SPEC | grep -q "@altlinux" ; then
			echo "Add changelog with initial build"
			add_changelog $SPEC -e "- initial build for ALT Sisyphus"
	fi


	echog "DONE"
done