#!/bin/ash

# See: Dockerfile
UID=431
GID=402

# Grab origin
ORIGIN=`git remote get-url origin`

echo "Setting access to /var/run/docker.sock."
chown -v $UID:$GID /var/run/docker.sock

echo "Setting read access to /etc/lixonet/."
chown -R $UID:$GID /etc/lixonet/
chmod -R 440 /etc/lixonet/
chmod -R a+X /etc/lixonet/

echo "Setting exclusive read access to SSH keys."
chmod -v 400 /etc/lixonet/id_rsa
chmod -v 400 /etc/lixonet/*/id_rsa
chmod -v 400 /etc/lixonet/known_hosts
stat /etc/lixonet/id_rsa
stat /etc/lixonet/*/id_rsa
stat /etc/lixonet/known_hosts

echo "Enabling write access to /etc/lixonet/version."
touch /etc/lixonet/version
chmod 660 /etc/lixonet/version
stat /etc/lixonet/version

if [ "$1" == "force" ]; then
   echo 0 > /etc/lixonet/version
fi

docker rm -f lixonet-ee
docker build -t lixonet-ee . && \
docker run --restart always -d \
   -e DOCKER_HOST=unix:///var/run/docker.sock \
   -e GIT_URL=$ORIGIN \
   -v /var/run/docker.sock:/var/run/docker.sock \
   -v /etc/lixonet:/etc/lixonet \
   -v /etc/lixonet/known_hosts:/root/.ssh/known_hosts \
   -v /etc/lixonet/id_rsa:/root/.ssh/id_rsa \
   --name lixonet-ee \
   lixonet-ee