# Get the current non-root user
CURRENT_USER=$(who | awk 'NR==1{print $1}')

# Executed after package installation
post_install() {
	# Check if Docker is installed
	if ! command -v docker >/dev/null 2>&1; then
		echo "The Docker package is not installed. Please install it before continuing."
		exit 1
	fi

	# Start the Duplicati container using docker-compose
    echo "Starting the Duplicati container..."

    # Expand $CURRENT_USER and execute docker-compose with eval
    eval "HOME=/home/$CURRENT_USER docker-compose -f /etc/docker-biglinux/duplicati/docker-compose.yml up -d"
    
    # Symlink docker-compose.yml to Docker/Duplicati folder
    echo "Creating symlink to docker-compose.yml..."
    ln -s /etc/docker-biglinux/duplicati/docker-compose.yml /home/$CURRENT_USER/Docker/Duplicati/docker-compose.yml
    
    # Set the correct owner and group for the Docker folder and its contents
    echo "Setting correct permissions for Docker folder..."
    chown -R $CURRENT_USER:$CURRENT_USER /home/$CURRENT_USER/Docker/Duplicati
}

# Upgrade package
post_upgrade() {
	post_install
}

# Executed before package removal
pre_remove() {
	# Stop and remove the Duplicati container
	echo "Stopping and removing Duplicati container..."
	docker-compose -f /etc/docker-biglinux/duplicati/docker-compose.yml down
	
	# Remove symlink to docker-compose.yml in Docker/Duplicati folder
    echo "Removing symbolic link to docker-compose.yml..."
    rm -f /home/$CURRENT_USER/Docker/Duplicati/docker-compose.yml
}

# Executed after package removal
post_remove() {
	# Remove the Docker image
    echo "Removing the Duplicati Docker image..."
    docker rmi linuxserver/duplicati:latest
}
