#!/bin/bash
#
#    Copyright (C) 2008-2010  Rubén Rodríguez <ruben@trisquel.info>
#    Copyright (C)      2014  Santiago Rodriguez <santi@trisquel.info>
#
#    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, write to the Free Software
#    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
#

set -e
export LANG=C LC_TIME=C
PACKAGE=$(echo $0 |/bin/sed s/make-//g)

export DATE=$(date +'%a, %d %b %Y %T %z')

export DATA=$PWD/DATA/$PACKAGE
if ! [ 1$COMPONENT = "1main" ]
then
    COMPONENT=${COMPONENT:-universe}
    export NO_PKG_MANGLE=1
fi

[ -d PACKAGES ] || mkdir PACKAGES

export DEBIAN_FRONTEND=noninteractive
export DEBEMAIL=trisquel-devel@listas.trisquel.info
export DEBFULLNAME="Trisquel GNU/Linux developers"
export CODENAME=flidas
export REVISION=8.0
export RELEASE=trisquel
export DOMAIN=trisquel.info
export UPSTREAM=xenial
export UPSTREAMRELEASE=16.04
MIRROR=http://archive.ubuntu.com/ubuntu
DEVELMIRROR=http://devel.trisquel.info/trisquel/$CODENAME
LOCALMIRROR=http://archive.trisquel.info/trisquel
LOCAL_APT=`mktemp -d` 

pkgversion(){
	dpkg-parsechangelog --show-field Version
}
replace(){
find $3 -type f -not -iregex '.*changelog.*' -not -iregex '.*copyright.*' -execdir /bin/sed --follow-symlinks -i s^"$1"^"$2"^g {} \;
}
changelog(){
head -n 1 debian/changelog | grep -q $UPSTREAM-security && REPO=$CODENAME-security || REPO=$CODENAME
[ "$BACKPORT" = true ] || [ "$BACKPORTS" = true ] && REPO=${CODENAME}-backports
echo | dch -D $REPO -v `pkgversion`+${REVISION}trisquel${VERSION} "$1"

# Make sure the changelog file is identical between archs
/bin/sed "/-- Trisquel/s/.*/ -- Trisquel GNU\/Linux developers <trisquel-devel@listas.trisquel.info>  $DATE/" -i debian/changelog
}


#Setup local apt

trap "rm -rf ${LOCAL_APT}" 0 HUP INT QUIT ILL ABRT FPE SEGV PIPE TERM

mkdir -p ${LOCAL_APT}/var/lib/apt/partial
mkdir -p ${LOCAL_APT}/var/cache/apt/archives/partial
mkdir -p ${LOCAL_APT}/etc/
mkdir -p ${LOCAL_APT}/var/lib/dpkg
touch ${LOCAL_APT}/var/lib/dpkg/status
touch ${LOCAL_APT}/etc/trusted.gpg
[ $UID = 0 ] && id _apt > /dev/null 2>&1 && chown _apt ${LOCAL_APT}  -R

cat << EOF > ${LOCAL_APT}/etc/apt.conf
Dir::State "${LOCAL_APT}/var/lib/apt";
Dir::State::status "${LOCAL_APT}/var/lib/dpkg/status";
Dir::Etc::SourceList "${LOCAL_APT}/etc/apt.sources.list";
Dir::Cache "${LOCAL_APT}/var/cache/apt";
pkgCacheGen::Essential "none";
Dir::Etc::Trusted "${LOCAL_APT}/etc/trusted.gpg";
EOF

export TRUSTEDFILE=${LOCAL_APT}/etc/trusted.gpg

if [ -f trusted.local.gpg ]
then
cp trusted.local.gpg "${LOCAL_APT}/etc/trusted.gpg"
else
# Trisquel key
apt-key --keyring ${LOCAL_APT}/etc/trusted.gpg adv --keyserver keyserver.ubuntu.com --recv-keys B4EFB9F38D8AEBF1 > /dev/null
# Ubuntu gpg keys
apt-key --keyring ${LOCAL_APT}/etc/trusted.gpg adv --keyserver keyserver.ubuntu.com --recv-keys 40976EAF437D05B5 > /dev/null
apt-key --keyring ${LOCAL_APT}/etc/trusted.gpg adv --keyserver keyserver.ubuntu.com --recv-keys 3B4FE6ACC0B21F32 > /dev/null
# Debian gpg keys
apt-key --keyring ${LOCAL_APT}/etc/trusted.gpg adv --keyserver keyserver.ubuntu.com --recv-keys 9D6D8F6BC857C906 > /dev/null
apt-key --keyring ${LOCAL_APT}/etc/trusted.gpg adv --keyserver keyserver.ubuntu.com --recv-keys 8B48AD6246925553 > /dev/null
fi

# Also import the repository key optionally listed in the helper
[ "1$REPOKEY" != "1" ] && apt-key --keyring ${LOCAL_APT}/etc/trusted.gpg adv --recv-keys --keyserver keyserver.ubuntu.com $REPOKEY

cat << EOF > ${LOCAL_APT}/etc/apt.sources.list
deb-src $MIRROR $UPSTREAM main universe
deb-src $MIRROR $UPSTREAM-updates main universe
deb-src $MIRROR $UPSTREAM-security main universe

EOF

[ "1$EXTERNAL" != "1" ] && eval echo "$EXTERNAL" >> ${LOCAL_APT}/etc/apt.sources.list

#Cleanup
rm -rf PACKAGES/$PACKAGE
mkdir PACKAGES/$PACKAGE
cd PACKAGES/$PACKAGE
[ $UID = 0 ] && id _apt > /dev/null 2>&1 && chown _apt .

#Get package and uncompress it
apt-get update -c $LOCAL_APT/etc/apt.conf
apt-get source $PACKAGE --download-only -c ${LOCAL_APT}/etc/apt.conf
# Verify it first
#   Import the key for the package uploader
#   Use the one listed in the helper if available, otherwise download the one listed in the dsc
if [ "1$SIGNKEY" != "1" ] ; then
  apt-key --keyring ${LOCAL_APT}/etc/trusted.gpg adv --recv-keys --keyserver keyserver.ubuntu.com $SIGNKEY > /dev/null
  gpgv --keyring ${LOCAL_APT}/etc/trusted.gpg *.dsc
else
  if grep -q "BEGIN PGP SIGNATURE" *.dsc; then
    KEY=$(gpgv --keyring ${LOCAL_APT}/etc/trusted.gpg *.dsc 2>&1 | grep "key ID" | sed 's/.*key ID //' || true)
    apt-key --keyring ${LOCAL_APT}/etc/trusted.gpg adv --recv-keys --keyserver keyserver.ubuntu.com $KEY > /dev/null
    gpgv --keyring ${LOCAL_APT}/etc/trusted.gpg *.dsc
  else
    echo WARNING! The dsc file is not gpg signed!
    [ -z "$EXTERNAL" ] && exit 1
  fi
fi

dpkg-source --no-check -x --skip-patches *.dsc source

find -maxdepth 1 -type f | xargs rm
cd source

#disable 3.0 deb source format
[ -f debian/source/format ] && rm debian/source/format
[ -f debian/source/options ] && rm debian/source/options

#for i in debian.master/control.stub.in debian.master/control.stub debian.master/control debian/control.stub.in debian/control.stub debian/control
#do
#    [ -f $i ] && /bin/sed "s_^Maintainer.*_Maintainer: $DEBFULLNAME <$DEBEMAIL>_g" -i $i
#done

compile(){


PROCESSORS=1
if [ 1$PARALLEL != "1false" ]
then
    PROCESSORS=$(grep processor /proc/cpuinfo | wc -l)
fi


if [ 1$QUILT != 1skip ]; then
export QUILT_PATCHES=debian/patches
grep -qv '^#' debian/patches/series 2>/dev/null && quilt push -a
fi

cd ..
dpkg-source -b source
rm -rf ${LOCAL_APT}
echo "Trisquel source package built!"

}

sedhelper2(){
  FILE="$1"
  EXPR="$2"";"

  while [ 1"$EXPR" != 1 ];do
    SUBEXPR=$(cut -d\; -f 1 <<< "$EXPR")
    MD5=$(md5sum "$FILE")
    echo Running modification-aware sed: sed "$SUBEXPR" -i "$FILE"
    /bin/sed "$SUBEXPR" -i "$FILE"
    if [ "$MD5" = "$(md5sum "$FILE")" ]; then
      echo File "$FILE" was not modified, stopping.
      exit 1
    fi
    EXPR=$(cut -d\; -f 2- <<< "$EXPR" )
    echo $EXPR | egrep ';' -q || break
  done
}

sedhelper(){
  FILE="$1"
  EXPR="$2"

  MD5=$(md5sum "$FILE")
  echo Running modification-aware sed: sed "$EXPR" -i "$FILE"
  /bin/sed "$EXPR" -i "$FILE"
  if [ "$MD5" = "$(md5sum "$FILE")" ]; then
    echo File "$FILE" was not modified, stopping.
    exit 1
  fi
}

sed (){
if ! echo $@ | grep -qw '\-i'; then
  echo Running fallback sed: /bin/sed "$@"
  /bin/sed "$@"
else

[ 1"$1" = "1-i" ] && shift

  SEDEXPR="$1"
  shift
  for FILE in "$@"; do
  [ 1"$FILE" = "1-i" ] && continue
  if [ -f "$FILE" ]; then
    sedhelper "$FILE" "$SEDEXPR"
  else
    echo File "$FILE" does not exist, stopping.
    exit 1
  fi
  done
fi
}


