#!/bin/sh

work=$1

systemctl is-active --quiet docker || service docker start

createdev() {
    dd if=/dev/zero of=$1 bs=1K count=$2
    mkfs.ext4 -F $1
    tune2fs -L "$3" $1
}

mountdev() {
    if [ ! -d $2 ]; then
	mkdir -p $2
    fi
    mount -o loop $1 $2
}

if [ -z $work ]; then
    work=/root/epygi/ecqx
fi

if [ ! -d $work ]; then
    mkdir -p $work
fi

rootdev=$(mount|grep ' / '|cut -d' ' -f 1)
if [ -b $rootdev ]; then
    avail=$(df -k --output=avail "$rootdev" | tail -n1)
    # reserve for update
    # avail=$(($avail-968312))
fi

sconf=204800
slang=56413
slog=512000
s=$(($sconf+$slang+$slog))
sdata=$(($avail-$s))


if [ ! -f $work/config.img ]; then
    createdev $work/config.img $sconf "CONFIG"
fi
if [ ! -f $work/lang.img ]; then
    createdev $work/lang.img $slang "LANGUAGE"
fi
if [ ! -f $work/log.img ]; then
    createdev $work/log.img $slog "LOG"
fi
if [ ! -f $work/data.img ]; then
    createdev $work/data.img $sdata "BBRAM"
fi

if [ ! -f $work/image.bin ]; then
    echo error: no image
    exit 1
fi

if [ ! -d $work/config ]; then
    mkdir $work/{config,data,lang,update,factory}
    mkdir $work/factory/factorysafedir
fi

mountdev $work/config.img $work/config
mountdev $work/lang.img $work/lang
mountdev $work/log.img $work/log
mountdev $work/data.img $work/data

docker stop ecqx

docker container prune -f

docker rmi ecqx/img

docker image prune -f -a

tar -C $work/img -c . | docker import - ecqx/img

umount $work/img

docker volume create --driver local \
		--opt type=tmpfs \
		--opt device=tmpfs \
		ramdisk

PUBLIC_HOSTNAME=$(/opt/aws/bin/ec2-metadata | grep 'public-hostname:' | cut -d ' ' -f 2)

sysctl -w kernel.sched_rt_runtime_us=-1

echo "DISABLE_KERNEL_MODULES=yes" > $work/features
echo "RENAME_NET_INTERFACE=yes" >> $work/features
echo "RUN_VIA_DOCKER=yes" >> $work/features

docker run -d --name ecqx -h $PUBLIC_HOSTNAME -e "DISABLE_KERNEL_MODULES=yes" -e "RENAME_NET_INTERFACE=yes" -e "RUN_VIA_DOCKER=yes" --network host --privileged --cap-add NET_ADMIN --cap-add SYS_NICE --cap-add SYS_MODULE \
		--volume $work/config:/mnt/flashfs:rw \
		--volume $work/data:/mnt/bbram:rw \
		--volume ramdisk:/mnt/ramdisk:rw \
		--volume $work/factory:/mnt/factory:rw \
		--volume $work/lang:/mnt/lang:rw \
		--volume $work/update:/mnt/update:rw \
		--volume /run/systemd:/run/systemd \
		--volume $work:/mnt/epdocker \
		--read-only -it ecqx/img /bin/sh -c "/etc/rc.d/rc.local start ; /bin/softdogd ; tail -f /dev/null"

