Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env perl6
- use LibCurl::HTTP;
- use JSON::Fast;
- sub MAIN ( Bool :d(:$debug) ) {
- my $ZONE_NAME = '[HOST]';
- my $ZONE_ID = '[HASH]';
- my $LOGIN_EMAIL = '[EMAIL]';
- my $API_KEY = '[KEY]';
- my $start_time = time;
- my $browser = LibCurl::HTTP.new;
- $browser.useragent("perl6 LibCurl");
- $browser.set-header(
- X-Auth-Email => "$LOGIN_EMAIL",
- X-Auth-Key => "$API_KEY"
- );
- my %current_ips;
- %current_ips<4> = $browser.GET(
- "http://ipv4.icanhazip.com"
- ).perform.content;
- debug($browser, "get ipv4", $debug);
- %current_ips<6> = $browser.GET(
- "http://ipv6.icanhazip.com"
- ).perform.content;
- debug($browser, "get ipv6", $debug);
- my $records_json = $browser.GET(
- "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/dns_records"
- ).perform.content;
- debug($browser, "get records", $debug);
- my %records_hash := from-json $records_json;
- my @records := %records_hash<result>;
- my Int $updated = 0;
- for @records -> %record {
- my Str $current_ip;
- if ("%record<type>" eq 'A') {
- # IPV4
- next if (%record<content> ne %current_ips<4>);
- $current_ip = %current_ips<4>;
- } elsif (%record<type> eq 'AAAA') {
- # IPV6
- next if (%record<content> ne %current_ips<6>);
- $current_ip = %current_ips<6>;
- }
- say "Need to update record %record<name>, has content: %record<content>, should be $current_ip";
- my Str $record_id = %record<id>;
- my %data = (
- "type" => "%record<type>",
- "name" => "%record<name>",
- "content" => "$current_ip"
- );
- my Str $json_data = to-json %data;
- try {
- CATCH {
- say "FATAL ERROR";
- debug($browser, "perform update of $record_id from %record<content> to $current_ip", $debug);
- }
- $browser.setopt(
- URL => "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/dns_records/$record_id",
- send => "$json_data"
- ).perform;
- }
- debug($browser, "perform update of $record_id from %record<content> to $current_ip", $debug);
- say "Done";
- $updated++;
- }
- my Int $seconds = time - $start_time;
- print "All done";
- if ($updated > 0) {
- print ". Updated $updated records in $seconds seconds.\n";
- } else {
- print " in $seconds seconds. No updates performed.\n";
- }
- }
- sub debug(
- LibCurl::HTTP $browser,
- Str $label,
- Bool $debug
- ) {
- if ! $browser.success {
- fail "HTTP error performing $label.";
- };
- if $debug {
- say "\n--- Debug output for $label ---";
- say "Status: ", $browser.statusline;
- say "Headers: ", $browser.receiveheaders.perl;
- say "Content: ", $browser.content;
- say "--- END DEBUG ---";
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement