#!/bin/bash

date_stamp=$(date +%Y%m%d)

[ -d /usr/portage ] || mkdir /usr/portage
chown portage:portage /usr/portage

# world packages
mv /var/lib/portage/world "/var/lib/portage/world.bck-${date_stamp}"
cp "clients/${CLIENT}/world" /var/lib/portage/world
chown root:portage /var/lib/portage/world
chmod 644 /var/lib/portage/world

# portage files

item="/etc/portage/make.conf"
mv "${item}" "${item}.bck-${date_stamp}"
cp "clients/${CLIENT}/portage/$(basename ${item})" "${item}"

file_list=(/etc/portage/package.keywords \
/etc/portage/package.mask \
/etc/portage/package.unmask \
/etc/portage/package.use \
/etc/portage/repos.conf \
)
for item in ${file_list[*]}
do
  # clients/${CLIENT}/portage/${item}
  filename=$(basename "${item}")
  if [ -d "${item}" ]; then
    echo "INFO: ${item} : OK"
  elif [ -f "${item}" ]; then
    echo "INFO: ${item} : file - fixing"
    mv "${item}" "${item}.bck-${date_stamp}"
    mkdir -p "${item}"
    mv "${item}.bck-${date_stamp}" "${item}"
  else
    echo "INFO: ${item} : missing - fixing"
    mkdir -p "${item}"
  fi

  if [ ! -d "${item}" ]; then
    echo "ERROR: ${item} missing!"
    exit 1
  fi

  if [ -d "clients/${CLIENT}/portage/${filename}" ]; then
    # only non-empty directory
    if [ -n "$(ls  "clients/${CLIENT}/portage/${filename}")" ]; then
      cp clients/"${CLIENT}"/portage/"${filename}"/* "${item}"
    fi
  elif [ -f "clients/${CLIENT}/portage/${filename}" ]; then
    cp "clients/${CLIENT}/portage/${filename}" "${item}"
  else
    echo "WARNING: customisation is not available "
    echo "WARNING:   (clients/${CLIENT}/portage/${filename}"
  fi
done

## WA (20190813): circle dependency
#USE="-tk -sqlite" emerge =dev-lang/python-3.5.5

# WA (20220108): circle dependency
USE="-lz4" emerge app-arch/libarchive

# gentoo portage utils
emerge gentoolkit eix ccache
#mycmd="emerge gentoolkit eix ccache"
#if $mycmd; then
#  ret=$?
#  echo "ERROR: executing $mycmd"
#  echo "ERROR: returned $ret"
#  exit 1
#fi 

ccache -M 2G
[ -d /var/cache/eix ] || mkdir -p /var/cache/eix
chown  portage:portage /var/cache/eix
eix-update
