#!/bin/sh
#     Name:  gparted
#  Purpose:  Perform appropriate startup of GParted executable gpartedbin.
#
#            The purpose of these startup methods is to prevent
#            devices from being automounted, and to ensure only one
#            instance of GParted is running.  File system problems can
#            occur if devices are mounted prior to the completion of
#            GParted's operations, or if multiple partition editing
#            tools are in use concurrently.
#
# Copyright (C) 2008, 2009, 2010, 2013, 2015 Curtis Gedak
#
#  This file is part of GParted.
#
#  GParted is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  GParted is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with GParted.  If not, see <http://www.gnu.org/licenses/>.
#

#
#  Only permit one instance of GParted to execute at a time
#
# 目的 : 以适当的方式运行 Gparted 的可执行程序 gpartedbin
# 这些启动方法的目的是防止设备自动安装，并确保只有一个GParted实例正在运行。如果在GParted操作完成之前安装设备，或者同时使用多个分区编辑工具，则可能会出现文件系统问题。
# 一次只允许执行一个 Gparted 实例

# 导入环境变量
if test "x`id -u`" != "x0" ; then
    echo "start write env ......"
    env > /tmp/.gparted
    echo "write env end !"
fi

# 检测单例
if test "z`ps -e | grep gpartedbin`" != "z"; then
	running_uid=$(cat /tmp/.gparted.uid)
	my_uid=$(id -u)
	if [ "$running_uid" != "$my_uid" ] ; then
                # lang=`locale | awk 'NR==1' | awk -F '=' '{print $2}'`
		lang=$(locale | grep '^LANG=' | awk -F '=' '{print $2}' | cut -d '.' -f 1)

		case "$lang" in
			"zh_CN")
				notify-send -a "分区编辑器" -i "gparted" "分区编辑器" "其他用户已经运行分区编辑器"
				;;
			"zh_HK")
				notify-send -a "分區編輯器" -i "gparted" "分區編輯器" "其他用戶已經運行分區編輯器"
				;;
			"mn_MN")
				notify-send -a "ᠬᠤᠪᠢᠶᠠᠷᠢ ᠳᠤᠭᠤᠷᠢᠭ᠎ᠤᠨ ᠨᠠᠢᠷᠠᠭᠤᠯᠤᠭᠤᠷ" -i "gparted" "ᠬᠤᠪᠢᠶᠠᠷᠢ ᠳᠤᠭᠤᠷᠢᠭ᠎ᠤᠨ ᠨᠠᠢᠷᠠᠭᠤᠯᠤᠭᠤᠷ" "ᠪᠤᠰᠤᠳ ᠬᠡᠷᠡᠭᠯᠡᠭᠴᠢ ᠨᠢᠭᠡᠨᠲᠡ ᠲᠣᠭᠣᠷᠢᠭ ᠬᠤᠪᠢᠶᠠᠨ ᠨᠠᠶᠢᠷᠠᠭᠤᠯᠤᠭᠴᠢ ᠶᠢ ᠠᠵᠢᠯᠯᠠᠭᠤᠯᠵᠠᠢ ᠃"
				;;
			"bo_CN")
				notify-send -a "བག་ལེབ་ཀོར་མོ།" -i "gparted" "བག་ལེབ་ཀོར་མོ།" "སྤྱོད་མཁན་གཞན་དག་གིས་ཡན་ལག་ཁུལ་གྱི་རྩོམ་སྒྲིག་ཡོ་བྱད་བེད་སྤྱོད་བྱས་ཡོད།"
				;;
			*)
				notify-send -a "gparted" -i "gparted" "gparted" "gparted is already running"
				;;
		esac
	fi

	echo "The process gpartedbin is already running."
	echo "Only one gpartedbin process is permitted."
	# snow modify it in 2021-06-07 14:17:21
        # add activation window fun
        display_old="echo ${DISPLAY}"
        export DISPLAY=":0"
        gparted_pid=`ps -e | grep gpartedbin | awk '{print $1}'`
        gparted_win_id=`wmctrl -p -G -l | grep "${gparted_pid}" | head -1 | awk '{print $1}'`
        echo "active gparted win , win id is ${gparted_win_id}"
        wmctrl -i -a "${gparted_win_id}"
        export DISPLAY="${display_old}"
	exit 1
fi

# 第一次运行 , 存储 uid
if test "x`id -u`" != "x0" ; then
    uid=`id -u`
    echo "$uid" > /tmp/.gparted.uid
fi

# 定义执行 Gparted 的基本命令
BASE_CMD="/usr/sbin/gpartedbin $*"

# 如果不是 root 权限 , 用 su 进行提权
if test "x`id -u`" != "x0"; then
	# 如果没有 su 程序 , 用普通用户运行 , 弹出错误框
	if test "xpkexec --disable-internal-agent" = "x"; then
		echo "Root privileges are required for running gparted."
		$BASE_CMD
		exit 1
	fi

	#
	# Interim workaround to allow GParted run by root access to the
	# X11 display server under Wayland.  If configured with
	# './configure --enable-xhost-root', the xhost command is
	# available and root has not been granted access to the X11
	# display via xhost, then grant access.
	#
	ENABLE_XHOST_ROOT=no
	GRANTED_XHOST_ROOT=no
	if test "x$ENABLE_XHOST_ROOT" = 'xyes' && xhost 1> /dev/null 2>&1; then
		if ! xhost | grep -qi 'SI:localuser:root$'; then
			xhost +SI:localuser:root
			GRANTED_XHOST_ROOT=yes
		fi
	fi

	#
	# Run gparted as root.
	#
	pkexec --disable-internal-agent '/usr/sbin/gparted' "$@"
	status=$?

	#
	# Revoke root access to the X11 display, only if we granted it.
	#
	if test "x$GRANTED_XHOST_ROOT" = 'xyes'; then
		xhost -SI:localuser:root
	fi
	exit $status
fi

# 检测 systemd 是否存在 , 并且 守护进程是否在运行
HAVE_SYSTEMCTL=no
for k in '' `echo "$PATH" | sed 's,:, ,g'`; do
	if test -x "$k/systemctl"; then
		if test "z`ps -e | grep systemd`" != "z"; then
			HAVE_SYSTEMCTL=yes
			break
		fi
	fi
done

#begin

# 导致文件管理器侧边栏的 u 盘消失 , 故注释

# 检测 udisks2-inhibit 是否存在于已知位置 , 并且 守护进程是否在运行
HAVE_UDISKS2_INHIBIT=no
#if test -x "/usr/lib/udisks2/udisks2-inhibit"; then
#	if test "z`ps -e | grep 'udisksd'`" != "z"; then
#		HAVE_UDISKS2_INHIBIT=yes
#	fi
#fi

#end

# 检测 udisks 是否存在 , 并且 守护进程是否在运行
HAVE_UDISKS=no
for k in '' `echo "$PATH" | sed 's,:, ,g'`; do
	if test -x "$k/udisks"; then
		if test "z`ps -e | grep udisks-daemon`" != "z"; then
			HAVE_UDISKS=yes
			break
		fi
	fi
done

# 检测 hal-lock 是否存在 , 并且 守护进程是否在运行
HAVE_HAL_LOCK=no
for k in '' `echo "$PATH" | sed 's,:, ,g'`; do
	if test -x "$k/hal-lock"; then
		if test "z`ps -e | grep hald`" != "z"; then
			HAVE_HAL_LOCK=yes
			break
		fi
	fi
done

# begin

# 该命令会导致文件管理器侧边栏的 u 消失 , 故做更改
# 使用 systemctl 通过屏蔽当前未屏蔽的挂载点来防止自动装载
#if test "x$HAVE_SYSTEMCTL" = "xyes"; then
#	MOUNTLIST=`systemctl list-units --full --all -t mount --no-legend \
#	  | grep -v masked | cut -f1 -d' ' \
#	  | egrep -v '^(dev-hugepages|dev-mqueue|proc-sys-fs-binfmt_misc|run-user-.*-gvfs|sys-fs-fuse-connections|sys-kernel-config|sys-kernel-debug)'`
#	systemctl --runtime mask --quiet -- $MOUNTLIST
#fi

if test "x$HAVE_SYSTEMCTL" = "xyes"; then
        MOUNTLIST=`systemctl show --all --property=Where,What,Id,LoadState '*.mount' | \
        awk '
        function clear_properties() {
                where = ""; what = ""; id = ""; loadstate = ""
        }
        function process_unit() {
                if (substr(what,1,5) == "/dev/"     &&
                    loadstate        != "masked"    &&
                    what             != "/dev/fuse" &&
                    ! (substr(what,1,9) == "/dev/loop" && substr(where,1,6) == "/snap/"))
                {
                        print id
                }
                clear_properties()
        }
        /^Where=/     { where     = substr($0,7) }
        /^What=/      { what      = substr($0,6) }
        /^Id=/        { id        = substr($0,4) }
        /^LoadState=/ { loadstate = substr($0,11) }
        /^$/          { process_unit() }
        END           { process_unit() }
        '`
        systemctl --runtime mask --quiet -- $MOUNTLIST
fi

# end

#
# Create temporary blank overrides for all udev rules which automatically
# start Linux Software RAID array members.
#
# Udev stores volatile / temporary runtime rules in directory /run/udev/rules.d.
# Older versions use /dev/.udev/rules.d instead, and even older versions don't
# have such a directory at all.  Volatile / temporary rules are use to override
# default rules from /lib/udev/rules.d.  (Permanent local administrative rules
# in directory /etc/udev/rules.d override all others).  See udev(7) manual page
# from various versions of udev for details.
#
# Default udev rules containing mdadm to incrementally start array members are
# found in 64-md-raid.rules and/or 65-md-incremental.rules, depending on the
# distribution and age.  The rules may be commented out or not exist at all.
#
UDEV_TEMP_MDADM_RULES=''  # List of temporary override rules files.
for udev_temp_d in /run/udev /dev/.udev; do
	if test -d "$udev_temp_d"; then
		test ! -d "$udev_temp_d/rules.d" && mkdir "$udev_temp_d/rules.d"
		udev_mdadm_rules=`egrep -l '^[^#].*mdadm (-I|--incremental)' /lib/udev/rules.d/*.rules 2> /dev/null`
		UDEV_TEMP_MDADM_RULES=`echo "$udev_mdadm_rules" | sed 's,^/lib/udev,'"$udev_temp_d"','`
		break
	fi
done
for rule in $UDEV_TEMP_MDADM_RULES; do
	touch "$rule"
done

#
#  Use udisks2-inhibit if udisks2-inhibit exists and deamon running.
#  Else use both udisks and hal-lock for invocation if both binaries exist and both
#  daemons are running.
#  Else use udisks if binary exists and daemon is running.
#  Otherwise use hal-lock for invocation if binary exists and daemon is running.
#  If the above checks fail then simply run gpartedbin.
#
if test "x$HAVE_UDISKS2_INHIBIT" = "xyes"; then
	/usr/lib/udisks2/udisks2-inhibit $BASE_CMD
elif test "x$HAVE_UDISKS" = "xyes" && test "x$HAVE_HAL_LOCK" = "xyes"; then
	udisks --inhibit -- \
		hal-lock --interface org.freedesktop.Hal.Device.Storage --exclusive \
			--run "$BASE_CMD"
elif test "x$HAVE_UDISKS" = "xyes"; then
	udisks --inhibit -- $BASE_CMD
elif test "x$HAVE_HAL_LOCK" = "xyes"; then
	hal-lock --interface org.freedesktop.Hal.Device.Storage --exclusive \
		--run "$BASE_CMD"
else
	$BASE_CMD
fi

#
# Clear any temporary override udev rules used to stop udev automatically
# starting Linux Software RAID array members.
#
for rule in $UDEV_TEMP_MDADM_RULES; do
	rm -f "$rule"
done

# 使用 systemctl 恢复上面更改的任何挂载点的状态
if test "x$HAVE_SYSTEMCTL" = "xyes"; then
	systemctl --runtime unmask --quiet -- $MOUNTLIST
fi
