#!/bin/bash

source /etc/profile
config=/etc/rtc_plan.conf

close_power_on(){
    local DATE_MMM=`date -d"+5 year" +"%F %T"`
    rtcwake -m no --local --date="${DATE_MMM}"
}

close_power_off(){
    sed -i '/poweroff/d' /etc/crontabs/root
    /etc/init.d/cron restart >/dev/null &
}


time_list_sort(){
    local time_list=($1)
    local len=${#time_list[@]}     
    for((i=0; i<$len; i++)){
      for((j=i+1; j<$len; j++)){     
        if [[ "${time_list[i]}" > "${time_list[j]}" ]]; then
            local temp=${time_list[i]}
            time_list[i]=${time_list[j]}
            time_list[j]=$temp
        fi
      }
    }
    echo ${time_list[@]}
}

parse_json_list(){
    local start_list=""
    local stop_list=""
    local list_keys=`jq -r '.list|to_entries|map(.key)|.[]' $config`
    for item_key in $list_keys; do
        local item_action=`jq -r ".list.${item_key}.action" $config`
        local item_timelist=`jq -r ".list.${item_key}.timelist|.[]" $config`
        if [ "$item_action" = "start" ]; then
            start_list="$start_list $item_timelist"
        else
            stop_list="$stop_list $item_timelist"
        fi
    done
    if [ ! -z "$start_list" ]; then
        start_list=`time_list_sort "$start_list"`
        power_on_alarm "$start_list"
    else
        close_power_on
    fi
    if [ ! -z "$stop_list" ]; then
        power_off_alarm "$stop_list"
    else
        close_power_off
    fi
}

power_on_alarm(){
    local start_list=($1)
    local current_week=`date +"%w"`
    local current_time=`date +"%w%H%M"`
    local alarm_time=""
    for item_time in ${start_list[@]}; do
        [[ "$current_time" > "$item_time" ]] && continue
        [ "$current_time" = "$item_time" ] && continue
        alarm_time=$item_time
        break
    done
    [ -z "$alarm_time" ] && alarm_time=${start_list[0]}
    local week=${alarm_time:0:1}
    local hour=${alarm_time:1:2}
    local minute=${alarm_time:3}
    let days_ago=current_week-week
    [ $days_ago -gt 0 ] && let days_ago=days_ago-7
    local alarm_point="`date -d "$days_ago days ago" +"%F"` ${hour}:${minute}:00"
    rtcwake -m no --local --date="$alarm_point"
}

power_off_alarm(){
    sed -i '/poweroff/d' /etc/crontabs/root
    local stop_list=($1)
    for item_time in ${stop_list[@]}; do
        local week=${item_time:0:1}
        local hour=${item_time:1:2}
        local minute=${item_time:3}
        echo "$minute $hour * * $week /sbin/poweroff" >> /etc/crontabs/root
    done
    /etc/init.d/cron restart >/dev/null &
}

hwclock -w
if [ ! -e $config ]; then
    close_power_on
    close_power_off
    exit 0
fi

enable=`jq -r .enable $config`
if [ "$enable" != "1" ]; then
	close_power_on
    close_power_off
    exit 0
else
    parse_json_list
fi

exit 0
