#!/bin/bash
# BASIC SETTINGS change at wish

# set maximum hours EPG data available needed for updating automatic recorder schedule
# equivalent to maximum period system will not wake up if no future recording is found
epg_hours=36

# enable check for active users ("yes" or "no"/whatever)
check_users=yes

# enter active processes to be checked
# just extend / edit the array, for more or less processes...
# if not needed, set variable to "no", otherwise to "yes"
check_processes=yes
processes[0]=process_one
#processes[1]=process_two

# check your router settings for information about ip-addresses in use
# active addresses, IP Addresses, or Hostnames.
# just extend / edit the array, for more or less addresses / hostnames!
# if not needed, set the variable to "no", otherwise to "yes"
check_addresses=yes
addresses[0]=PCNameClient1
addresses[1]=PCNameClient2


# set idle time in minutes before shutdown
idle_time_shutdown=20

# set login and pwd from TvHeadEnd
login_name=UsernameForLogin
password=UserPasswordForLogin

# minimum time in seconds needed for consecutive shutdown AND startup
safe_margin_shutdown=600
# minimum time in seconds needed to start up the computer properly
safe_margin_startup=180

# Flag if logging active
logging_active=yes
# Timestamp in File (beginnging of line)
tmstmp=$(date +"%Y-%m-%d %H:%M:%S")
# LogFile Name (file will be created / append, on start of script)
logfile=/var/log/Powersave_$(date +"%Y-%m-%d").log


###############################
# the script! nothing to change here!!!
##############################

#   initial recording status do not change
recording=1


echo "$tmstmp => starting powersave script..." >> $logfile

#   check for shutdown
    until [ $recording -eq 0 ];do
    	if [ $logging_active = "yes" ]; then
		tmstmp=$(date +"%Y-%m-%d %H:%M:%S")
        	echo "$tmstmp => beginning loop. recording status: $recording" >> $logfile
	fi

	#reset shutdown timer
        shutdown_timer=$idle_time_shutdown
	if [ $logging_active = "yes" ]; then
	        tmstmp=$(date +"%Y-%m-%d %H:%M:%S")
        	echo "$tmstmp => setting shutdown timer" >> $logfile
        fi

#       countdown to shutdown
        until [ $shutdown_timer -eq 0 ];do
	    if [ $logging_active = "yes" ]; then
               	tmstmp=$(date +"%Y-%m-%d %H:%M:%S")
	        echo "$tmstmp => beginning loop. shutdown timer: $shutdown_timer" >> $logfile
	    fi

#           countdown
            shutdown_timer=$((shutdown_timer-1))

#           check for subscription status
            TvH_status=$(curl --user $login_name:$password http://127.0.0.1:9981/status.xml | grep '<subscriptions>' | awk -F '>' '{print $2}' | awk -F '<' '{print $1}')
            until [ $TvH_status -eq  0 ];do
                if [ $logging_active = "yes" ]; then
                    tmstmp=$(date +"%Y-%m-%d %H:%M:%S")
                    echo "$tmstmp => checking subscription status: $TvH_status" >> $logfile
                fi
                sleep 60s
                TvH_status=$(curl --user $login_name:$password http://127.0.0.1:9981/status.xml | grep '<subscriptions>' | awk -F '>' '{print $2}' | awk -F '<' '{print $1}')
                if [ $TvH_status -eq 0 ]; then
                    shutdown_timer=$idle_time_shutdown
                    tmstmp=$(date +"%Y-%m-%d %H:%M:%S")
                    echo "$tmstmp => subscription active, set shutdown timer to: $shutdown_timer sec" >> $logfile
                fi
            done

            sleep 60s

#           check for active users
            if [ $check_users = "yes" ]; then
                if [ $logging_active = "yes" ]; then
                    tmstmp=$(date +"%Y-%m-%d %H:%M:%S")
                    echo "$tmstmp => checking active users" >> $logfile
                fi
                if [ $(who | wc -l) -ne 0 ]; then
                    shutdown_timer=$idle_time_shutdown
	            tmstmp=$(date +"%Y-%m-%d %H:%M:%S")
        	    echo "$tmstmp => users active, set shutdown timer to: $shutdown_timer sec" >> $logfile
                fi
            fi

#           check for active clients
            if [ $logging_active = "yes" ]; then
                tmstmp=$(date +"%Y-%m-%d %H:%M:%S")
                echo "$tmstmp => checking smbstatus" >> $logfile
            fi
            if [ $(smbstatus -L | grep 'No locked files' | wc -l) -ne 1 ]; then
                shutdown_timer=$idle_time_shutdown
                tmstmp=$(date +"%Y-%m-%d %H:%M:%S")
                echo "$tmstmp => samba connection active, set shutdown timer to: $shutdown_timer sec" >> $logfile
            fi

#           check for possible clients
            total_clients=0
            if [ $check_addresses = "yes" ]; then
                if [ $logging_active = "yes" ]; then
                    tmstmp=$(date +"%Y-%m-%d %H:%M:%S")
                    echo "$tmstmp => checking active addresses" >> $logfile
                fi
                for i in "${addresses[@]}"; do
                    counter_c=$( ping -c3 $i | grep 'received' | awk -F ',' '{print $2}' | awk '{print $1}' )
                    total_clients=$((total_clients+counter_c))
                done
            fi
            if [ $total_clients -ne 0 ]; then
                shutdown_timer=$idle_time_shutdown
                tmstmp=$(date +"%Y-%m-%d %H:%M:%S")
                echo "$tmstmp => clients actiive, set shutdown timer to $shutdown_timer sec" >> $logfile
            fi


#	    check for active processes
	    total_processes=0
	    if [ $check_processes = "yes" ]; then
	        if [ $logging_active = "yes" ]; then
                    tmstmp=$(date +"%Y-%m-%d %H:%M:%S")
                    echo "$tmstmp => checking processes" >> $logfile
	         fi
        	 for i in "${processes[@]}"; do
                    counter_p=$( ps -A | grep -i '$i' | wc -l )
	            total_processes=$((total_processes+counter_p))
        	 done
	    fi
            if [ $total_processes -ne 0 ]; then
	        shutdown_timer=$idle_time_shutdown
                tmstmp=$(date +"%Y-%m-%d %H:%M:%S")
                echo "$tmstmp => processes active, set shutdown timer to: $shutdown_timer sec" >> $logfile
            fi



        done

#       retrieve and calculate wake up data
        if [ $logging_active = "yes" ]; then
            tmstmp=$(date +"%Y-%m-%d %H:%M:%S")
            echo "$tmstmp => getting next recording" >> $logfile
        fi
        if [ $(curl --user $login_name:$password http://127.0.0.1:9981/status.xml | grep '<subscriptions>' | awk -F '>' '{print $2}' | awk -F '<' '{print $1}') -eq 0 ]; then
            if [ $(curl --user $login_name:$password 127.0.0.1:9981/status.xml | grep "<next>" | awk -F '>' '{print $2}' | awk -F '<' '{print $1}' | wc -l) -eq 0 ]; then
                wake_after_min=$((epg_hours*60))
            else
                wake_after_min=$(curl --user $login_name:$password 127.0.0.1:9981/status.xml | grep "<next>" | awk -F '>' '{print $2}' | awk -F '<' '{print $1}')
            fi
        else
            wake_after_min=0
        fi
        wake_after_secs=$((wake_after_min*60))

        if [$logging_active = "yes" ]; then
            tmstmp=$(date +"%Y-%m-%d %H:%M:%S")
            echo "$tmstmp => wake_after_secs: $wake_after_secs" >> $logfile	
        fi

#       check safe margin shutdown
        if [ $safe_margin_shutdown -lt $wake_after_secs ]; then
            recording=0
        else
            recording=1
        fi

#       check for active post recording processes
        total_processes=0
        if [ $check_processes = "yes" ]; then
            if [ $logging_active = "yes" ]; then
                tmstmp=$(date +"%Y-%m-%d %H:%M:%S")
                echo "$tmstmp => checking processes" >> $logfile
            fi
            for i in "${processes[@]}"; do
                counter_p=$( ps -A | grep $i | wc -l )
                total_processes=$((total_processes+counter_p))
            done
        fi
        if [ $total_processes -ne 0 ]; then
            recording=1
        fi

    done

#   set max time for updating automatic recorder schedule
#   equivalent to maximum period system will not wake up
    epg_secs=$((epg_hours*3600))
    current_date=$(date +%s)
    wake_date=$((current_date+epg_secs))

#   set wake up time
    wake_date_tmp=$((current_date+wake_after_secs-safe_margin_startup))
    if [ $wake_date_tmp -lt $wake_date ]; then
        wake_date=$wake_date_tmp
    fi

#   set RTC wake up time
    if [ $logging_active = "yes" ]; then
        tmstmp=$(date +"%Y-%m-%d %H:%M:%S")
	tmpWakeDate=$(date -d @$wake_date "+%Y-%m-%d %H:%M:%S")
        echo "$tmstmp => setting wake up time: $wake_date ($tmpWakeDate)" >> $logfile
    fi
    echo 0 > /sys/class/rtc/rtc0/wakealarm
    echo $wake_date > /sys/class/rtc/rtc0/wakealarm

#   shutdown computer
    if [ $logging_active = "yes" ]; then
        tmstmp=$(date +"%Y-%m-%d %H:%M:%S")
        echo "$tmstmp => shutting down" >> $logfile
    fi
    sudo shutdown -h now
fi


