#! /bin/bash
# This script wraps the devtoolset-4 repository for CentOS-6 as an RPM-package.
# The eclipes packages are excluded for now.
#
# 0.4		fill in readonly directories correctly as non-root
#
# Used with e.g.
# isv:ownCloud:devel:Qt562/devtoolset-4-centos-6-x86-64
#
# test with 
install_test='docker run -ti -v /var/tmp/build-root/CentOS_6-x86_64:/CentOS_6-x86_64 centos:centos6 sh -x -c "yum update -y; yum install -y /CentOS_6-x86_64/home/abuild/rpmbuild/RPMS/x86_64/*x86_64.rpm; test -f /opt/rh/devtoolset-4/enable && . /opt/rh/devtoolset-4/enable; c++ -v; exec /bin/bash"'

generator=$(basename $0)
version=0.4

pkgname=devtoolset-4-centos6-x86-64
upstream_repo=http://mirror.centos.org/centos/6/sclo/x86_64/rh/devtoolset-4/
cutdirs=5	# leave only devtoolset-4 as a directory.
extra_dependencies="
Provides: devtoolset-4-centos6
# file /usr/lib64/libatomic.so.1.1.0 conflicts with package libatomic-4.9.0-6.1.1.el6.x86_64
# file /usr/lib64/libitm.so.1.0.0 conflicts with package libitm-4.9.0-6.1.1.el6.x86_64
# file /usr/share/info/libitm.info.gz conflicts with file from package libitm-4.9.0-6.1.1.el6.x86_64
Obsoletes: libatomic < 4.9.1, libitm < 4.9.1
Conflicts: libatomic < 4.9.1, libitm < 4.9.1
"
# pkgname=devtoolset-4-centos7-x86-64
# upstream_repo=http://mirror.centos.org/centos/7/sclo/x86_64/rh/devtoolset-4/
# cutdirs=5	# leave only devtoolset-4 as a directory.
extra_dependencies="
Provides: devtoolset-4-centos7 devtoolset-4-centos
"

pkgvers=0.1_oc$(date +"%Y%m%d")

tmpdir=/tmp/dt-$$/

mkdir -p $tmpdir
( cd $tmpdir; wget -r -nH --cut-dirs=$cutdirs -np $upstream_repo )
find $tmpdir -type f -a ! -name \*.rpm -print0 | xargs -0 -r rm -f
find $tmpdir -name \*.src.rpm          -print0 | xargs -0 -r rm -f
find $tmpdir -name \*-eclipse-\*       -print0 | xargs -0 -r rm -f

test "$0" != "$generator" && cp $0 $generator

rm -rf scripts; mkdir -p scripts
:> dependencies
## Must loop aphabetically sorted, so that newest version number comes last.
## We weed out older versions by using uniquename.
for pkg in $tmpdir/*/*.rpm; do
  rpm -qp --nosignature --requires $pkg  | sed -e 's@^@Requires: @'  >> dependencies
  rpm -qp --nosignature --provides $pkg  | sed -e 's@^@Provides: @'  >> dependencies
  rpm -qp --nosignature --obsoletes $pkg | sed -e 's@^@Obsoletes: @' >> dependencies
  rpm -qp --nosignature --conflicts $pkg | sed -e 's@^@Conflicts: @' >> dependencies
  uniquename=$(echo $pkg | sed -e 's@-[0-9][^-]*-[0-9][^-]*.\(x86_64\|i586\|noarch\).rpm$@.\1.rpm@')
  test "$pkg" != "$uniquename" && mv $pkg $uniquename
  base=$(basename $uniquename .rpm)
  out=scripts/$base.none
  rpm -qp --nosignature --scripts $uniquename | while read -r line; do
    case "$line" in

      "postinstall scriptlet (using /bin/sh):")
        out=scripts/$base.postinstall
        ;;

      "postuninstall scriptlet (using /bin/sh):")
        out=scripts/$base.postuninstall
        ;;

      "preinstall scriptlet (using /bin/sh):")
        out=scripts/$base.preinstall
        ;;

      "preuninstall scriptlet (using /bin/sh):")
        out=scripts/$base.preuninstall
        ;;

      "postinstall program: "*)
        out=scripts/$base.postinstall
        echo $line | sed -e 's@^postinstall program: @@' >> $out
        out=scripts/$base.none
        ;;

      "postuninstall program: "*)
        out=scripts/$base.postuninstall
        echo $line | sed -e 's@^postuninstall program: @@' >> $out
        out=scripts/$base.none
        ;;

      *)
        echo $line >> $out
        ;;
    esac
  done
done

cat <<EOF_SPEC1 > $pkgname.spec
# ATTENTION: DO NOT EDIT. this file is generated by $0.
# ATTENTION: It will be overwritten by the next run. 
Name:           $pkgname
Version:        $pkgvers
Release:        1
License:        GPL
BuildRoot:      %{_tmppath}/%{name}-%{version}-build
Group:          Development
Summary:        CentOS-6 devtoolset as a package.
Source:         $pkgname.tar.bz2
Source1:        $pkgname-scripts.tar.bz2
Source2:        $generator
# rpm provides /usr/bin/rpm2cpio
BuildRequires:  rpm cpio	
AutoReqProv:    no

# Disable /usr/lib/rpm/find-debuginfo.sh
# It crashes with Failed to write file: invalid section entry size
%define debug_package %{nil}

EOF_SPEC1
sort -u dependencies | egrep -v '^Requires: (libcilkrts |scl\-utils|devtoolset\-4\-(eclipse|mvn)|rh\-java\-common\-|maven30\-|libasan2 |liblsan |libmpx |libtsan |libubsan )' >> $pkgname.spec
cat <<EOF_SPEC2 >> $pkgname.spec
$extra_dependencies

%description
Tar ball created with 
$0 VERSION $version using
upstream_repo=$upstream_repo

%prep
%setup -T -c

%build
tar xvf %{S:0}

%install
set +x
for pkg in */*.rpm; do
  rpm -qp --nosignature \$pkg
  # cpio creates, fills then chmods missing directories. This is good.
  # But cpio chmods existing dirs before filling in. This is a bug.
  # Workaround: extract to an empty dir, then merge.
  mkdir cpiotmp						# empty dir
  rpm2cpio \$pkg | (cd cpiotmp && cpio -idmu --quiet)		# extract while creating all dirs.
  find cpiotmp        -type d -print0 | xargs -0 -r chmod u+rx	# assert accessible directories.
  find cpiotmp        -type f -print0 | xargs -0 -r chmod u+r	# assert readable files.
  find %{buildroot}   -type d -print0 | xargs -0 -r chmod u+rwx 	# assert writable dirs at the final destination
  (cd cpiotmp; find . -type f -print0 | cpio -pdm0 --quiet %{buildroot})	# copy over only files, creating dirs as needed.
  chmod u+rwx -R cpiotmp; rm -rf cpiotmp		# erase even when readonly.
done
set -x
# # extra hacks: I need my files readable and my dirs writable
# # to avoid
# # create archive failed on file .../opt/rh/devtoolset-4/root/usr/bin/staprun: cpio: Bad magic
# # rm: cannot remove .../opt/rh/devtoolset-4/root/usr/lib64/perl5/vendor_perl/Authen: Permission denied
# chmod -R u+r %{buildroot}/*
# find %{buildroot} -type d -print0 | xargs -0 -r chmod u+w

mkdir -p %{buildroot}/usr/share/%{name}
tar xvf %{S:1} -C %{buildroot}/usr/share/%{name}
ls -la %{buildroot}/usr/share/%{name}/*

%clean
rm -rf "%{buildroot}"

%files
%defattr(-,root,root)
/opt/*
/usr/*
/etc/*

%pre
## FIXME: we don't have our scripts before installation
for s in /usr/share/%{name}/scripts/*.preinstall; do
  sh \$s \$1 || true
done

%preun
for s in /usr/share/%{name}/scripts/*.preuninstall; do
  sh \$s \$1
done

%post
## FIXME: /sbin/restorecon: No such file or directory
for s in /usr/share/%{name}/scripts/*.postinstall; do
  sh \$s \$1 || true
done

%postun
## FIXME: we no longer have our scripts after uninstall
for s in /usr/share/%{name}/scripts/*.postuninstall; do
  sh \$s \$1 || true
done

%changelog
EOF_SPEC2


tar jcvf $pkgname-scripts.tar.bz2 scripts
rm -rf scripts
tar jcvf $pkgname.tar.bz2 -C $tmpdir .
rm -rf $tmpdir

osc add $pkgname.tar.bz2 
osc add $pkgname-scripts.tar.bz2
osc add $pkgname.spec 
osc add $generator

cat << EOF
Build with

 osc build *.spec CentOS_6

Test install with

 $install_test

EOF
