#!/bin/bash

mydir=$(dirname "$0")

dbpwd="$1"
if [ -z "$dbpwd" ]; then
    echo "Usage: $0 <database-password>" 1>&2
    exit 2
fi

set -eu -o pipefail

rootdir="$mydir/../.."

deploydir="$rootdir"/deploy
if [ ! -d "$deploydir" ]; then
    echo "ERROR: Unexpected repository layout - expected directory at $deploydir"
    exit 2
fi

managerdir="$deploydir/docker"
if [ ! -d "$managerdir" ]; then
    echo "ERROR: Required directory $managerdir not found"
    exit 2
fi

configdir="$deploydir/config"
if [ ! -d "$configdir" ]; then
    echo "ERROR: Required directory $configdir not found"
    exit 2
fi

if [ ! -f "$rootdir/postgres-dumpall" ]; then
    echo "ERROR: I expect to find a Postgres SQL multi-db dump file in $rootdir/postgres-dumpall"
    exit 2
fi

fontdir="$rootdir"/public/themes/soundsoftware/stylesheets/fonts
if [ ! -f "$fontdir/24BC0E_0_0.woff" ]; then
    echo "ERROR: I expect to find necessary webfonts in $fontdir"
    exit 2
fi

for f in database.yml code.conf ; do
    cat "$configdir/$f.in" |
        sed 's/INSERT_POSTGRES_PASSWORD_HERE/'"$dbpwd"'/g' > \
            "$configdir/$f"
done

provisioning_commands=$(
    for x in "$deploydir"/provision.d/[0-9]*; do
        echo "RUN /bin/bash /var/www/code/deploy/provision.d/$(basename $x)"
    done | sed 's/$/\\n/' | fmt -2000 | sed 's/ RUN/RUN/g' )

( echo
  echo "### DO NOT EDIT THIS FILE - it is generated from Dockerfile.in"
  echo
) > "$managerdir/Dockerfile"

cat "$managerdir/Dockerfile.in" |
    sed 's,INSERT_PROVISIONING_HERE,'"$provisioning_commands"',' >> \
        "$managerdir/Dockerfile"

cd "$rootdir"

dockertag="cannam/soundsoftware-site"

sudo docker build -t "$dockertag" -f "deploy/docker/Dockerfile" .
sudo docker run -p 8080:80 -d "$dockertag"

