#!/bin/bash

if [ ! $1 ]; then
	echo "请不要忘记输入: -s /媒体库目录"
	exit
fi

        if command -v ifconfig >/dev/null 2>&1; then
                docker0=$(ifconfig docker0 | grep "inet " |awk '{print $2}'|tr -d "addr:" |head -n1)
        else
                docker0=$(ip addr show docker0 |grep "inet " |awk '{print $2}'|tr -d "addr:" |head -n1|cut -f1 -d/)
        fi

local_sha=$(docker inspect --format='{{index .RepoDigests 0}}' xiaoyaliu/glue:latest  |cut -f2 -d:)
#remote_sha=$(curl --ipv4 -s "https://hub.docker.com/v2/repositories/xiaoyaliu/glue/tags/latest"|grep -oP '(?<="digest":")[^"]+' |tail -n1 |cut -f2 -d:)
remote_sha=$(curl --ipv4 -s "https://hub.docker.com/v2/repositories/xiaoyaliu/glue/tags/latest"|grep -o '"digest":"[^"]*' | grep -o '[^"]*$'  |tail -n1 |cut -f2 -d:)
if [ ! "$local_sha" == "$remote_sha" ]; then
	docker rmi xiaoyaliu/glue:latest 2>/dev/null
	docker pull xiaoyaliu/glue:latest
fi

if [ $2 ]; then	
	docker run -i --security-opt seccomp=unconfined --rm -v $1:/media -v $2:/etc/xiaoya -e LANG=C.UTF-8  xiaoyaliu/glue:latest /update.sh
	if [ ! -f $2/emby_server.txt ]; then
		echo http://$docker0:6908 > $2/emby_server.txt
	fi
else
	docker run -i --security-opt seccomp=unconfined --rm -v $1:/media -v /etc/xiaoya:/etc/xiaoya -e LANG=C.UTF-8  xiaoyaliu/glue:latest /update.sh
	if [ ! -f /etc/xiaoya/emby_server.txt ]; then
                echo http://$docker0:6908 > /etc/xiaoya/emby_server.txt
        fi
fi
