#!/bin/bash

CONFIG=~/fritzbox_set_dect_ring_block.conf

# Please store your FritzBox data in the file $CONFIG
# in the format
# IP="192.168.178.1"
# FRITZUSER=""
# FRITZPW="this_is_my_password"
if [ ! -e $CONFIG ]
then
  echo "Please store your FritzBox data in $CONFIG"
  exit
fi
source $CONFIG

DECT_NUMBER=$1
START_HH=$2
START_MM=$3
END_HH=$4
END_MM=$5

if [[ "$DECT_NUMBER" == "" ]]
then
  echo "Please provide number of your DECT phone as first parameter, which should be changed, e.g. 3"
  exit
fi

if [[ "$START_HH" == "" ]]
then
  echo "Please provide start hour as second parameter, e.g. 10"
  exit
fi

if [[ "$START_MM" == "" ]]
then
  echo "Please provide start minute as third parameter, e.g. 27"
  exit
fi

if [[ "$END_HH" == "" ]]
then
  echo "Please provide end hour as fourth parameter, e.g. 22"
  exit
fi

if [[ "$END_MM" == "" ]]
then
  echo "Please provide end minute as fifth parameter, e.g. 52"
  exit
fi

challenge=$(curl -s "http://$IP/login_sid.lua?username=$FRITZUSER" | grep -Po '(?<=<Challenge>).*?(?=</Challenge>)')
md5=$(echo -n ${challenge}"-"$FRITZPW | iconv -f ISO8859-1 -t UTF-16LE | md5sum -b | awk '{print substr($0,1,32)}') 
response="${challenge}-${md5}"
sid=$(curl -i -s -k -d "response=${response}&username=$FRITZUSER" "http://$IP" | grep -Po -m 1 '(?<=sid=)[a-f\d]+' | tail -1)

curl http://$IP/data.lua -d "sid=${sid}xhr=1&page=edit_dect_ring_block&idx=${DECT_NUMBER}&lockmode=0&nightsetting=1&lockday=everyday&starthh=${START_HH}&startmm=${START_MM}&endhh=${END_HH}&endmm=${END_MM}&apply=" >/dev/null 2>&1
