#! /bin/bash

#set -e
set -x

SNAP_LIST="core18 gnome-3-28-1804"
SEED_PATH="/var/lib/snapd/seed/"
SEED_YAML="/var/lib/snapd/seed/seed.yaml"
SNAP_ID=0
OEM_PACKAGE="oem-workaround-snapd-preseed-lp1831230"
OEM_PACKAGE_VER="1.0sutton2"
OEM_PACKAGE_SHA="f7cd6650a4d4b8a305bb23cac11d5b01e87ac4f9792b5b41e2bc30e13d2c49bf949ebe444e97bf70c902ee62c443c91263e85790561912cc720c4241c77bc9e6"
SNAPS_DIR="/usr/share/snapd/"

# Make sure the snap has problem when seeding.
function check_snap_status()
{
	# Check the seed file first.
	if [ ! -e $SEED_YAML ]; then
		exit 0;
	fi
	# Check the snap process.
	SNAP_ID=`pidof /usr/bin/snap` 
	if [ -z $SNAP_ID ]; then
		exit 0
	fi
	# Check the snap process parameter.
	snap_process=`ps -q $SNAP_ID -ho command | cut -d ' ' -f 2-4`
	if [ "$snap_process" != "wait system seed.loaded" ]; then
		exit 0;
	fi
}

# Remove the snap package and reinstall, preload the preseed snaps without waiting.
function restore_snap()
{
	# Get the source package.
	wget -c -P ${SNAPS_DIR} http://oem.archive.canonical.com/updates/pool/public/o/${OEM_PACKAGE}/${OEM_PACKAGE}_${OEM_PACKAGE_VER}.tar.xz

	if [ ! -e ${SNAPS_DIR}${OEM_PACKAGE}_${OEM_PACKAGE_VER}.tar.xz ]; then
		exit 1
	fi

	SHA=`sha512sum ${SNAPS_DIR}${OEM_PACKAGE}_${OEM_PACKAGE_VER}.tar.xz | cut -d ' ' -f1`
	if [ $SHA != $OEM_PACKAGE_SHA ]; then
		exit 1
	fi

	# Backup the seed.yaml file
	cp $SEED_YAML $SEED_YAML.bak
	snap abort --last=seed
	# stop snapd and snapd.socket
	systemctl stop snapd.socket
	systemctl stop snapd

	# Unpack the tar.gz package
	tar xf ${SNAPS_DIR}${OEM_PACKAGE}_${OEM_PACKAGE_VER}.tar.xz -C ${SNAPS_DIR}
	cp ${SNAPS_DIR}${OEM_PACKAGE}/seeds/snaps/*.snap ${SEED_PATH}snaps/
	cp ${SNAPS_DIR}${OEM_PACKAGE}/seeds/assertions/*.assert ${SEED_PATH}assertions/

	# Merged the seed.yaml
	sed -i '6,9d' $SEED_YAML
	sed -i '5a\  -\n    name: core18\n    channel: stable\n    file: core18_970.snap\n  -\n    name: gnome-3-28-1804\n    channel: stable/ubuntu-18.04\n    file: gnome-3-28-1804_55.snap' $SEED_YAML

	# stop snapd and snapd.socket
	systemctl start snapd
	systemctl start snapd.socket
	# Sometimes it won't work, we will restart it to double confirm it could work.
	# It could work after next reboot if it's still fail to initilize.
	sleep 3
	systemctl restart snapd

	if [ -e ${SNAPS_DIR} ];  then
		rm -rf ${SNAPS_DIR}
	fi
}

if [ -f /etc/buildstamp ]; then
	# We only fix the snaps issue on released configs.
	timestamp=`tail -n1 /etc/buildstamp | grep -o '[^-]\+-[^-]\+$'`
	case $timestamp in
		20190425-103 | 20190516-111 | 20190522-109 | 20190523-122)
		check_snap_status
		restore_snap
		;;
		*) exit 0 ;;
	esac
fi
