#!/bin/bash

_closeyad()
{
	if [ $(ps alxxx | grep "ARandR 解像度の設定" | grep -v grep | wc -l) -gt 0 ] ; then
		kill $(ps alxxx | grep "ARandR 解像度の設定" | grep -v grep | \
			grep -o "^\S\+\s\+\S\+\s\+\S\+" | grep -o "\S\+$")
	fi
}

nohup yad --title "ARandR 解像度の設定" \
	--width=400 --border=10 --center --on-top \
	--image=display --window-icon=display \
	--text "  画面の変更を適用するには
  「<span background='#ffff66'>メニューバー＞Layout＞適用 </span>」を選択してください。
  
  また、次回起動時にも同じ設定を使用したい場合は、
  「<span background='#ffff66'>メニューバー＞Layout＞別名で保存 </span>」を選択し、
  適当な名前を付けて保存してください。
  自動的に設定を抽出し、適切なフォルダに配置します。" 2>&1 > /dev/null &


file=$(strace arandr 2>&1 > /dev/null | grep chmod | grep '\.sh"' | \
	tail -n 1 | grep -o '\".*\"' | grep -o '[^"]*')
	
if [ "a${file}" == "a" ] ; then
	_closeyad
	exit 1
fi

exec=$(cat "${file}" | grep xrandr)
if [ "a${exec}" == "a" ] ; then
	_closeyad
	exit 1
fi

echo "[Desktop Entry]
Type=Application
Name=ARandR
Name[ja]=ARandR 解像度の設定
Comment=Setting screen resolution and dual monitor placement
Comment[ja]=解像度やデュアルモニターの配置を設定します
Exec=${exec}
Icon=display
" > ${HOME}/.config/autostart/arandr.desktop

rm -f "${file}"
rm -rf "${HOME}/.screenlayout"
_closeyad
exit 0

