#!/usr/bin/env bash

set -e

SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
cd $SCRIPT_DIR
cd $(git rev-parse --show-toplevel)

ARCH=${1}
HOSTNAME=${2}
SSH=${3}
CONTAINER=${4}

OPTIONAL_CONTAINER=
if [ -n "$CONTAINER" ]; then
  OPTIONAL_CONTAINER="-container-${CONTAINER}"
fi 

nix build --system ${ARCH} ".#secrets-init-${HOSTNAME}${OPTIONAL_CONTAINER}"
nix-copy-closure --to ${SSH} --use-substitutes $(readlink result)
ssh ${SSH} "$(readlink result)/bin/secrets-init-${HOSTNAME}${OPTIONAL_CONTAINER}"