#!/bin/bash

DIR="$PWD"

if ! [ -f "$1" ]; then
  echo "$1 is not a path to a file"
  exit 1
fi
if ! file "$1" | grep -q 'gzip compressed data'; then
  echo "$1 is not a BPM package"
  exit 1
fi
if ! tar -tf "$1" | grep -q 'source.sh'; then
  echo "$1 is not a BPM source package"
  exit 1
fi
echo "$Converting $1..."

PKGINFO_FILE=$(tar -axf "$1" pkg.info -O)
declare -A PKGINFO
while read line; do
  PKGINFO[$(echo -n "$line" | cut -d":" -f1 | xargs)]=$(echo -n "$line" | cut -d":" -f2 | xargs)
done < <(tar -axf "$1" pkg.info -O)

TEMPDIR="/var/tmp/bpm_source_${PKGINFO[name]}"
if [ -d "$TEMPDIR" ]; then
  rm -rf "$TEMPDIR"
fi
mkdir -p "$TEMPDIR"
mkdir -p "$TEMPDIR"/source
mkdir -p "$TEMPDIR"/output
tar -xf "$1" -C "$TEMPDIR" source.sh

cd "$TEMPDIR"

export BPM_PKG_NAME="${PKGINFO[name]}"
export BPM_PKG_DESC="${PKGINFO[description]}"
export BPM_PKG_VERSION="${PKGINFO[version]}"
export BPM_PKG_URL="${PKGINFO[url]}"
export BPM_PKG_ARCH="${PKGINFO[architecture]}"
IFS=',' read -r -a BPM_PKG_DEPENDS <<< "${PKGINFO[depends]}"
IFS=',' read -r -a BPM_PKG_MAKE_DEPENDS <<< "${PKGINFO[make_depends]}"
export BPM_PKG_DEPENDS
export BPM_PKG_MAKE_DEPENDS
export BPM_WORKDIR="$TEMPDIR"
export BPM_SOURCE="$TEMPDIR"/source
export BPM_OUTPUT="$TEMPDIR"/output

source source.sh

if [[ $(type -t prepare) == function ]]; then
  echo "Running prepare() function..."
  export -f prepare
  fakeroot bash -e -c prepare
  if [ $? -ne 0 ]; then
    echo "Failed to run prepare() function in source.sh"
    exit 1
  fi
fi
cd "$BPM_SOURCE"
if [[ $(type -t build) == function ]]; then
  echo "Running build() function..."
  export -f build
  fakeroot bash -e -c build
  if [ $? -ne 0 ]; then
    echo "Failed to run build() function in source.sh"
    exit 1
  fi
fi
cd "$BPM_SOURCE"
if [[ $(type -t check) == function ]]; then
  echo "Running check() function..."
  export -f check
  fakeroot bash -e -c check
  if [ $? -ne 0 ]; then
    echo "Failed to run check() function in source.sh"
    exit 1
  fi
fi
if ! [[ $(type -t package) == function ]]; then
  echo "Failed to locate package() function in source.sh"
  exit 1
fi
echo "Running package() function..."
export -f package
fakeroot bash -e -c package
if [ $? -ne 0 ]; then
  echo "Failed to run package() function in source.sh"
  exit 1
fi
cd "$BPM_WORKDIR"
mv output/ files/
touch pkg.info
echo "${PKGINFO_FILE}" > pkg.info
sed -i "s/architecture:.*/architecture: $(uname -m)/g" pkg.info
sed -i 's/type:.*/type: binary/g' pkg.info
tar -czpf "$BPM_PKG_NAME".tar.gz files pkg.info
mv "$BPM_PKG_NAME".tar.gz "$DIR"/"$BPM_PKG_NAME"-"$(uname -m)".bpm
echo "Package conversion complete!"

rm -rf "$TEMPDIR" root
