#!/bin/bash

# Setup delay time (minutes)
delay=5

function chk_pciehp ()
{
check=`lsmod | grep pciehp`
if [ -z "$check" ] ; then
	echo "Loading PCIe Hotplug driver..."
	modprobe pciehp
else
	echo "PCIe Hotplug driver was loaded."
fi
}

function scan_dev ()
{
i=1
host=`lspci -d 197b:2382 | wc -l`
while [ $i -le $host ]
do
	dev[$i]=`lspci -d 197b:2382 | awk '{print $1}' | head -n$i | tail -n1`
#	echo ${dev[$i]}
	i=`echo "$i+1" | bc`
done
}

function acdc ()
{
i=1

while [ $i -le $host ]
do
dev=${dev[$i]}
if [ -z "$dev" ] ; then
	echo "JMicron JMB38x is not found!"
else
	probe=`lspci -s $dev -xxx | grep a0: | awk '{print $14}'`
	if [ -n "$probe" ] ; then
		if [ $probe = 40 ] ||
		   [ $probe = 41 ] ||
		   [ $probe = 42 ] ||
		   [ $probe = 43 ] ||
		   [ $probe = 44 ] ||
		   [ $probe = 45 ] ||
		   [ $probe = 46 ] ||
		   [ $probe = 47 ] ||
		   [ $probe = 48 ] ||
		   [ $probe = 49 ] ||
		   [ $probe = 4a ] ||
		   [ $probe = 4b ] ||
		   [ $probe = 4c ] ||
		   [ $probe = 4d ] ||
		   [ $probe = 4e ] ||
		   [ $probe = 4f ] ; then
			PWRMODE=1
			echo "JMB38X: Battery mode!!"
		else
			PWRMODE=0
			echo "JMB38X: AC power pluged!!"
		fi
	fi
fi
i=`echo "$i+1" | bc`
done
}

function d3e ()
{
i=1

while [ $i -le $host ]
do
dev=${dev[$i]}
if [ -z "$dev" ] ; then
	echo "JMicron JMB38x is not found!"
else
	probe=`lspci -s $dev -xxx | grep e0: | awk '{print $3}'`
if [ -n "$probe" ] ; then
	if [ $probe = 0c ] ||
	   [ $probe = 1c ] ||
	   [ $probe = 1c ] ||
	   [ $probe = 2c ] ||
	   [ $probe = 3c ] ||
	   [ $probe = 4c ] ||
	   [ $probe = 5c ] ||
	   [ $probe = 6c ] ||
	   [ $probe = 7c ] ||
	   [ $probe = 8c ] ||
	   [ $probe = 9c ] ||
	   [ $probe = ac ] ||
	   [ $probe = bc ] ||
	   [ $probe = cc ] ||
	   [ $probe = dc ] ||
	   [ $probe = ec ] ||
	   [ $probe = fc ] ; then
		setpci -s $dev D4=10:F0
		setpci -s $dev AD=FF
		setpci -s $dev AE=69
		echo "JMB38X: JMB38X D3e function is enabled!"
	else
		echo "JMB38X: There is a card inserted!"
	fi
fi
fi
i=`echo "$i+1" | bc`
done
}

function poll ()
{
i=1
time=`echo "$delay*60" | bc`
while :
do
	scan_dev
	if [ -f /sys/bus/usb/devices/1-5/power/level ]; then
	   echo auto > /sys/bus/usb/devices/1-5/power/level
	fi

	if [ -f /sys/bus/usb/devices/5-5/power/level ]; then
	   echo auto > /sys/bus/usb/devices/5-5/power/level
	fi
	sleep $time
	acdc
	if [ $PWRMODE -eq 1 ] ; then
		d3e
	fi
done
}

function main ()
{
	chk_pciehp
	poll
}

main
