#!/bin/bash
set -e

/system/internal/inituidgid

### Import signing key.
/system/internal/setuser app /tools/silence-unless-failed \
  gpg --batch --trust-model always --import /params/signing_key

### Make GPG non-interactive.
mv /usr/bin/gpg2 /usr/bin/gpg2.real
rm /usr/bin/gpg
cp /system/internal/dummygpg /usr/bin/gpg

### Sign packages.
echo " --> Signing packages"
/system/internal/setuser app \
  rpm --resign --define '%_signature gpg' --define "%_gpg_name $SIGNING_KEY" \
  /packages/*/*.rpm

### Import into repo.
cd /packages
PACKAGES=(*/*.rpm)
DIRS=()
echo " --> Importing ${#PACKAGES[*]} packages"

for F in "${PACKAGES[@]}"; do
  DIR=`dirname "$F"`
  DIRS+=("$DIR")

  mkdir -p "/repo/$DIR"
  echo "     $F"
  cp "$F" "/repo/$DIR/"
done

# $DIRS is now an array of distro-architecture directory names.
# We remove duplicates.
OUTPUT=`ruby -e 'puts ARGV.uniq.join("\n")' "${DIRS[@]}"`
IFS=$'\n'
DIRS=("$OUTPUT")

# Create a repo for each distro-architecture directory.
for DIR in ${DIRS[@]}; do
  echo " --> Updating $DIR"
  (cd "/repo/$DIR" && createrepo .)
done
