#!/usr/bin/perl -w

use Digest::MD5 "md5_hex";

# https://forum.fhem.de/index.php/topic,109689.15.html
# https://community.openhab.org/t/disable-internet-connection-of-specific-echo-device-on-fritz-box-via-script/91374

$config = "$ENV{HOME}/fritzbox_change_filter_profile.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 )
{
  die "Please store your FritzBox data in $config\n";
}
$FRITZPW = ''; # suppress warning
require $config;

#print "IP:        '$IP'\n";
#print "FRITZUSER: '$FRITZUSER'\n";
#print "FRITZPW:   '$FRITZPW'\n";

$filter_profile = shift || die "Please provide filter profile name as first parameter, e.g. filtprof890\n";

$time = shift || die "Please provide time limitation ('never' or 'unlimited') as second parameter.\n";

if ( $time ne 'never' && $time ne 'unlimited' )
{
  die "Please provide only time limitation values 'never' or 'unlimited' as second parameter.\n";
}

$challenge = `curl -s "http://$IP/login_sid.lua?username=$FRITZUSER"`;
chomp($challenge);
#print "Challenge: '$challenge'\n";
$challenge =~ s~.*<Challenge>(.+?)</Challenge>.*~$1~;
#print "Challenge: '$challenge'\n";

$md5 = "${challenge}-${FRITZPW}";
$md5 =~ s/(.)/$1.chr(0)/eg; # works probably only with ascii
# see: https://avm.de/fileadmin/user_upload/Global/Service/Schnittstellen/Session-ID_deutsch_13Nov18.pdf
$md5 = lc(md5_hex($md5));
$response = "$challenge-$md5";
#print "Response: '$response'\n";

$sid = `curl -s "http://$IP/login_sid.lua?response=${response}&username=$FRITZUSER"`;
chomp($sid);
#print "SID: '$sid'\n";
$sid =~ s~.*<SID>(.+?)</SID>.*~$1~;
#print "SID: '$sid'\n";

$result = `curl -s -d \"sid=${sid}&edit=${filter_profile}&time=${time}&budget=unlimited&apply=&page=kids_profileedit\" \"http://$IP/data.lua\"`;
if ($result =~ /"apply":"ok"/)
{
# print "OK.\n";
  exit 0;
}
else
{
  die "Fehler!\n";
}
