#!/usr/bin/env bash 
set -e
set -x

##
## PARAMS
##

OVERLAY_ROOTFS_PATH=${1:-/overlay-rootfs}
RELEASE_VERSION=${2:-1.6.0}

outputs=(
linux
portable
)

get_packages_with_versions_from_manifest() {
  # manifest
  manifest=$1

  # skarnet versions manifest
  curl -R -L \
      -o /tmp/manifest.txt \
      https://github.com/just-containers/skaware-builder/releases/download/v$RELEASE_VERSION/$manifest

  # parse manifest into s6 associative array
  versions=()
  while read -r line
  do
      key=`echo "${line}" | cut -d"=" -f1`
      value=`echo "${line}" | cut -d"=" -f2`
      if [[ ! -z "${key}" && ! -z "${value}" ]]; then
          versions+=("${key}-${value}")
      fi
  done < /tmp/manifest.txt

  # delete manifest
  rm /tmp/manifest.txt

  echo ${versions[@]}
}

##
## DOWNLOAD PACKAGES
##

# destination folder
cd /tmp

packages=($(get_packages_with_versions_from_manifest "manifest.txt"))
for package in "${packages[@]}"; do
  file=$package-linux-amd64-bin.tar.gz
  curl -R -L -O https://github.com/just-containers/skaware-builder/releases/download/v$RELEASE_VERSION/$file
done

# strace (if we want to debug)
if [ -n "$DEBUG" ]; then
  curl -R -L -o /tmp/strace http://landley.net/aboriginal/downloads/binaries/extras/strace-x86_64
fi

##
## OVERLAYS
##

for output in "${outputs[@]}"
do
  # overlay path
  overlaypath="$OVERLAY_ROOTFS_PATH-$output"

  # create overlay folder
  mkdir -p $overlaypath

  # copy overlay files
  cp -a $OVERLAY_ROOTFS_PATH/. $overlaypath/

  # skarnet versions manifest
  packages=($(get_packages_with_versions_from_manifest "manifest-$output.txt"))

  # install required binaries for this concrete output
  for package in "${packages[@]}"
  do
      tar xvfz /tmp/$package-linux-amd64-bin.tar.gz -C $overlaypath
  done

  # create must exist directories
  mkdir -p $overlaypath/etc/s6/init/env-stage2
  mkdir -p $overlaypath/etc/{cont-init.d,fix-attrs.d,services.d}
  mkdir -p $overlaypath/var/log/{s6-uncaught-logs,s6-fdholderd}

  # copy strace & fix permissions
  if [ -n "$DEBUG" ]; then
    cp /tmp/strace $overlaypath/usr/bin/strace
    chmod 0755 $overlaypath/usr/bin/strace
  fi

  # fix fix-attrs perms
  chmod 0755 $overlaypath/usr/bin/fix-attrs

  # fix init perms
  chmod 0755 $overlaypath/init
  chmod 0755 $overlaypath/etc/s6/init/init-stage*
  chmod 0755 $overlaypath/etc/s6/service/.s6-svscan/{crash,finish}
  chmod 0755 $overlaypath/etc/s6/service/s6-fdholderd/run
  chmod 0755 $overlaypath/etc/s6/service/s6-svscan-log/run

  # fix log folder perms
  chmod 2700 $overlaypath/var/log/{s6-uncaught-logs,s6-fdholderd}
  chown nobody:nogroup $overlaypath/var/log/{s6-uncaught-logs,s6-fdholderd}

  # dist!
  mkdir -p /dist
  tar -zcvf /dist/s6-overlay-$RELEASE_VERSION-$output-amd64.tar.gz -C $overlaypath ./
done
