#!/bin/bash
set -e

if [ $# -ne 1 ]; then
    echo "Usage: $0 tag" >/dev/stderr
    exit 1
fi

tag=$1

tgt=$(mktemp -d)

# Build fleet inside
docker run -v $PWD:/opt/fleet google/golang:1.4 /bin/bash -c "cd /opt/fleet && ./build"

# Generate manifest into target tmp dir
cat <<DF >${tgt}/manifest
{
   "acVersion" : "0.5.1",
   "acKind" : "ImageManifest",
   "name" : "coreos.com/fleetd",
   "labels" : [
      {
         "value" : "${tag}",
         "name" : "version"
      },
      {
         "name" : "os",
         "value" : "linux"
      }
   ],
   "app" : {
      "exec" : [
        "/bin/fleetd"
      ],
      "user" : "0",
      "group" : "0",
      "mountPoints" : [
         {
            "name" : "machine-id",
            "readOnly" : true,
            "path" : "/etc/machine-id"
         },
         {
            "path" : "/run/dbus/system_bus_socket",
            "readOnly" : false,
            "name" : "dbus-socket"
         },
         {
            "path" : "/run/fleet/units",
            "readOnly" : false,
            "name" : "fleet-units"
         },
         {
            "path" : "/etc/fleet",
            "readOnly" : true,
            "name" : "etc-fleet"
         }
      ]
   }
}
DF

# Create dirs and links
mkdir -p $tgt/rootfs/bin
mkdir -p $tgt/rootfs/etc/fleet
mkdir -p $tgt/rootfs/run/dbus
mkdir -p $tgt/rootfs/var
ln -s /run $tgt/rootfs/var/run

# Generate minimal hosts file
cat <<DF >${tgt}/rootfs/etc/hosts
127.0.0.1       localhost
::1             localhost ip6-localhost ip6-loopback
DF

# Copy fleetd binary
cp bin/fleetd $tgt/rootfs/bin

# Create resolv.conf file
touch $tgt/rootfs/etc/resolv.conf

# Build ACI
actool build -overwrite $tgt fleetd-${tag}.aci

# Validate ACI
actool validate fleetd-${tag}.aci

# Cleanup
rm -rf $tgt
