#!/bin/bash

myver='2.0'
startdir=`pwd`

[ -f /etc/makepkg.conf ] && source /etc/makepkg.conf

strip_url() {
  echo $1 | sed 's|^.*://.*/||g'
}

msg() {
	echo $* >&2
}

if [ "$1" = "--help" -o "$1" = "-h" ]; then
  shift
  echo "makepkg version $myver"
  echo "usage: $0 [options] [build_script]"
	echo "options:"
	echo "  -c, --clean   Clean up work files after build"
	echo "  -i, --install Install package after successful build"
	echo "  -h, --help    This help"
  echo
  echo "  if build_script is not specified, makepkg will look for a PKGBUILD"
  echo "  file in the current directory."
  echo
  exit 0
fi

CLEANUP=0
INSTALL=0

if [ "$1" = "-c" -o "$1" = "--clean" ]; then
	shift
	CLEANUP=1
fi
if [ "$1" = "-i" -o "$1" = "--install" ]; then
	shift
	INSTALL=1
fi

unset pkgname pkgver pkgrel pkgdesc
unset depends conflicts backup source install build
umask 0022


# check for a download utility
if [ -x /usr/bin/wget ]; then
 	ftpagent="/usr/bin/wget --passive-ftp --tries=3 --waitretry=3"
elif [ -x /usr/bin/snarf ]; then
 	ftpagent="/usr/bin/snarf"
elif [ -x /usr/bin/lftpget -a "$proto" = "ftp" ]; then
 	ftpagent="/usr/bin/lftpget"
else
 	msg "==> ERROR:  You need an ftp client installed (snarf/lftp/wget) in /usr/bin"
 	exit 1
fi

BUILDSCRIPT="./PKGBUILD"
if [ "$1" != "" ]; then
  BUILDSCRIPT=$1
fi

if [ ! -f $BUILDSCRIPT ]; then
  msg "==> ERROR:  $BUILDSCRIPT does not exist."
  exit 1
fi

source $BUILDSCRIPT

# check for no-no's
if [ `echo $pkgver | grep '-'` ]; then
	msg "==> ERROR:  pkgver is not allowed to contain hyphens."
	exit 1
fi
if [ `echo $pkgrel | grep '-'` ]; then
	msg "==> ERROR:  pkgrel is not allowed to contain hyphens."
	exit 1
fi

if [ `type -p pacman` ]; then
	msg "==> Checking Dependencies..."
	missdep=`pacman -T ${depends[@]}`
	ret=$?
	if [ "$ret" != "0" ]; then
		if [ "$ret" = "127" ]; then
			msg "==> ERROR: Dependency Check Failed:"
			msg ""
			nl=0
			for dep in $missdep; do
				echo -ne "$dep " >&2
				if [ "$nl" = "1" ]; then
					nl=0
					echo -ne "\n" >&2
					continue
				fi
				nl=1
			done
			msg ""
		else
			msg "==> ERROR: pacman returned a fatal error."
		fi
		exit 1
	fi
else
	msg "==> WARNING: pacman was not found in PATH. skipping dependency checks."
fi

d=`date`
msg "==> Making package $pkgname  ($d)"

# extract source
msg "==> Acquiring/Extracting Sources..."
mkdir -p src
cd $startdir/src
for netfile in ${source[@]}; do
  file=`strip_url $netfile`
  if [ -f ../$file ]; then
    msg "==> Found $file in build dir"
    cp ../$file .
  elif [ -f /var/cache/pacman/src/$file ]; then
    msg "==> Using local copy of $file"
    cp /var/cache/pacman/src/$file .
  else
    proto=`echo $netfile | sed 's|://.*||'`
    if [ "$proto" != "ftp" -a "$proto" != "http" ]; then
      msg "==> ERROR:  $netfile was not found in the build directory and is not a proper URL."
      msg "==> Aborting..."
      exit 1
    fi
    msg "==> Downloading $file"
    $ftpagent $netfile 2>&1
    if [ ! -f $file ]; then
      msg "==> ERROR: Failed to download $file"
      msg "==> Aborting..."
      exit 1
    fi
    mkdir -p /var/cache/pacman/src && cp $file /var/cache/pacman/src
  fi
  case $file in
	    *.tar.gz|*.tar.Z|*.tgz)
    cmd="tar --use-compress-program=gzip -xf $file" ;;
	    *.tar.bz2)
    cmd="tar --use-compress-program=bzip2 -xf $file" ;;
		  *.tar)
	  cmd="tar -xf $file" ;;
	    *.zip)
    cmd="unzip -qq $file" ;;
	    *)
    cmd="cp ../$file ." ;;
	esac
	msg "==> $cmd"
	$cmd
done

# check for existing pkg directory
if [ -d $startdir/pkg ]; then
	msg "==> Removing existing pkg directory..."
	rm -rf $startdir/pkg
fi
mkdir -p $startdir/pkg

# build
msg "==> Building Package..."
build 2>&1
if [ $? -gt 0 ]; then
  msg "==> Build Failed.  Aborting..."
  exit 2
fi

# get some package meta info
builddate=`date -u "+%a %b %d %k:%M:%S %Y"`
if [ "$PACKAGER" != "" ]; then
	packager="$PACKAGER"
else
	packager="Arch Linux (http://www.archlinux.org)"
fi
size=`du -cb $startdir/pkg | tail -1 | awk '{print $1}'`

# write the .PKGINFO file
msg "==> Generating .PKGINFO file..."
cd $startdir/pkg
echo "# Generated by makepkg $myver" >.PKGINFO
echo -n "# " >>.PKGINFO
date >>.PKGINFO
echo "pkgname = $pkgname" >>.PKGINFO
echo "pkgver = $pkgver-$pkgrel" >>.PKGINFO
echo "pkgdesc = $pkgdesc" >>.PKGINFO
echo "builddate = $builddate" >>.PKGINFO
echo "packager = $packager" >>.PKGINFO
echo "size = $size" >>.PKGINFO

for depend in "${depends[@]}"; do
  echo "depend = $depend" >>.PKGINFO
done
for conflict in "${conflicts[@]}"; do
  echo "conflict = $conflict" >>.PKGINFO
done
for bakfile in "${backup[@]}"; do
  echo "backup = $bakfile" >>.PKGINFO
done

# check for an install script
if [ "$install" != "" ]; then
	msg "==> Copying install script..."
	cp $startdir/$install $startdir/pkg/._install
fi

# remove info/doc files
cd $startdir
rm -rf pkg/usr/info pkg/usr/share/info
rm -rf pkg/usr/doc pkg/usr/share/doc

# move /usr/share/man files to /usr/man
if [ -d pkg/usr/share/man ]; then
	mkdir -p pkg/usr/man 
	cp -a pkg/usr/share/man/* pkg/usr/man/
	rm -rf pkg/usr/share/man
fi

# strip binaries
cd $startdir
msg "==> Stripping debugging symbols from libraries..."
find pkg/{,usr,usr/local}/lib -type f -exec /usr/bin/strip --strip-debug '{}' ';' 2>&1
msg "==> Stripping symbols from binaries..."
find pkg/{,usr,usr/local}/{bin,sbin} -type f -exec /usr/bin/strip '{}' ';' 2>&1

# tar it up
msg "==> Compressing package..."
cd $startdir/pkg
if [ -f $startdir/pkg/._install ]; then
	tar czvf $startdir/$pkgname-$pkgver-$pkgrel.pkg.tar.gz .PKGINFO ._install * >../filelist
else
	tar czvf $startdir/$pkgname-$pkgver-$pkgrel.pkg.tar.gz .PKGINFO * >../filelist
fi

cd $startdir
if [ "$CLEANUP" = "1" ]; then
	msg "==> Cleaning up"
	rm -rf src pkg
fi

d=`date`
msg "==> Finished making $pkgname  ($d)"

if [ "$INSTALL" = "1" ]; then
	msg "==> Running pacman --upgrade"
	pacman --upgrade $pkgname-$pkgver-$pkgrel.pkg.tar.gz
fi

exit 0
