#!/usr/local/bin/perl
# Show a form for creating or editing a DNS record

require './virtual-server-lib.pl';
&ReadParse();
$d = &get_domain($in{'dom'});
$d || &error($text{'edit_egone'});
&can_edit_domain($d) || &error($text{'edit_ecannot'});
&can_edit_records($d) || &error($text{'records_ecannot'});
&copy_alias_records($d) && &error($text{'records_ecannot2'});
&require_bind();
$tmpl = &get_template($d->{'template'});

if ($in{'type'}) {
	# Adding a new record
	if ($in{'type'} eq '$ttl') {
		$r = { 'defttl' => '1h' };
		}
	else {
		$r = { 'type' => $in{'type'},
		       'name' => ".".$d->{'dom'}."." };
		}
	&ui_print_header(&domain_in($d), $text{'record_title1'}, "");
	}
else {
	# Editing existing one
	($recs, $file) = &get_domain_dns_records_and_file($d);
	$file || &error($recs);
	($r) = grep { $_->{'id'} eq $in{'id'} } @$recs;
	$r || &error($text{'record_egone'});
	$r->{'defttl'} ||
	    $r->{'name'} eq $d->{'dom'}."." ||
	    $r->{'name'} =~ /\.\Q$d->{'dom'}\E\.$/ ||
		&error(&text('record_eunder', $r->{'name'}, $d->{'dom'}));
	&ui_print_header(&domain_in($d), $text{'record_title2'}, "");
	}

# Get type, verify editability
if ($r->{'defttl'}) {
	$t = { 'type' => '$ttl',
	       'desc' => $text{'records_typedefttl'} };
	}
else {
	($t) = grep { $_->{'type'} eq $r->{'type'} } &list_dns_record_types($d);
	}
&can_edit_record($d, $r) && $t || &error($text{'record_eedit'});
if ($d->{'dns_submode'}) {
	$cloud = &get_domain_dns_cloud(&get_domain($d->{'dns_subof'}));
	}
else {
	$cloud = &get_domain_dns_cloud($d);
	}

print &ui_form_start("save_record.cgi", "post");
print &ui_hidden("dom", $in{'dom'});
print &ui_hidden("type", $in{'type'});
print &ui_hidden("id", $in{'id'});
print &ui_hidden("show", $in{'show'});
print &ui_table_start($text{'record_header'}, undef, 2);

# Extract name and protocol from SRV
if ($r->{'type'} eq 'SRV' && $r->{'name'} =~ /^_([^\.]+)\._([^\.]+)\.(.*)/) {
	($sservice, $sproto) = ($1, $2);
	$r->{'name'} = $3;
	}

# Record name
if ($r->{'defttl'}) {
	# Default TTL has no name!
	}
elsif ($in{'type'} && $t->{'domain'}) {
	# New record, might be same as domain, or within it
	print &ui_table_row($text{'record_name'},
			    &ui_opt_textbox("name", undef, 20,
					    $text{'record_same'}).
			    "<tt>.$d->{'dom'}</tt>");
	}
elsif ($r->{'name'} eq $d->{'dom'}.".") {
	# Same as domain - disallow changes
	$name = $r->{'name'};
	$name =~ s/\.$//;
	print &ui_table_row($text{'record_name'},
			    "<tt>$name</tt>");
	}
else {
	# Within the domain
	$r->{'name'} =~ /^(\S*)\.\Q$d->{'dom'}\E\.$/ ||
		&error($text{'record_eparse'});
	$name = $1;
	print &ui_table_row($text{'record_name'},
			    &ui_textbox("name", $name, 20).
			    "<tt>.$d->{'dom'}</tt>");
	}

# Record type
print &ui_table_row($text{'record_type'}, $t->{'type'}." - ".$t->{'desc'});

if ($r->{'defttl'}) {
	# Default TTL for domain
	print &ui_table_row($text{'record_defttl'},
		&ttl_field("defttl", $r->{'defttl'}));
	}
else {
	# TTL for record
	print &ui_table_row($text{'record_ttl'},
		&ui_radio("ttl_def", $r->{'ttl'} ? 0 : 1,
			  [ [ 1, $text{'record_ttl1'} ],
			    [ 0, $text{'record_ttl0'} ] ])." ".
		&ttl_field("ttl", $r->{'ttl'}));

	# For SRV records, show name and protocol separately
	if ($r->{'type'} eq 'SRV') {
		print &ui_table_row($text{'record_sservice'},
			&ui_textbox("sservice", $sservice, 30));

		print &ui_table_row($text{'record_sproto'},
			&ui_select("sproto", $sproto || "tcp",
				[ [ "tcp", "TCP" ],
				  [ "udp", "UDP" ],
				  [ "tls", "TLS" ] ], undef, undef, 1));
		}

	# Values (type specific)
	@vals = @{$t->{'values'}};
	for(my $i=0; $i<@vals; $i++) {
		if ($vals[$i]->{'size'}) {
			$field = &ui_textbox("value_$i", $r->{'values'}->[$i],
					     $vals[$i]->{'size'});
			}
		elsif ($vals[$i]->{'opts'}) {
			$field = &ui_select("value_$i", $r->{'values'}->[$i],
					    $vals[$i]->{'opts'}, 1, 0,
					    $in{'type'} ? 0 : 1);
			}
		else {
			$field = &ui_textarea("value_$i", $r->{'values'}->[$i],
					     $vals[$i]->{'height'},
					     $vals[$i]->{'width'}, "soft");
			}
		$field .= " ".$vals[$i]->{'suffix'};
		if ($cloud && $cloud->{'proxy'} &&
		    $t->{'type'} =~ /^(A|AAAA|CNAME)$/ &&
		    $r->{'values'}->[0] !~ /^(127\.|::1)/) {
			$pc = $in{'type'} ? $tmpl->{'dns_cloud_proxy'}
					  : $r->{'proxied'};
			$field .= "&nbsp;&nbsp;".&ui_checkbox("proxyit", 1,
		                      $text{'records_typeprox'}, $pc);
			$field .= "
			<script>
				var ttl_def = document.querySelector('[name=\"ttl_def\"][value=\"1\"]'),
					ttl_val = document.querySelector('[name=\"ttl_def\"][value=\"0\"]'),
				    proxied = document.querySelector('[name=\"proxyit\"]');
				    if (ttl_val && proxied) {
					    ttl_val.addEventListener(\"click\", function() {
					    	proxied.checked = false;
					    });
					    proxied.addEventListener(\"click\", function() {
					    	this.checked && ttl_def.click()
					    });
				    }
			</script>";
			}
		print &ui_table_row($vals[$i]->{'desc'}, $field);
		}
	}

if (&supports_dns_comments($d)) {
	# Record comment
	print &ui_table_row($text{'record_comment'},
			    &ui_textbox("comment", $r->{'comment'}, 60));
	}

print &ui_table_end();
if ($in{'type'}) {
	print &ui_form_end([ [ undef, $text{'create'} ] ]);
	}
elsif (&can_delete_record($d, $r)) {
	print &ui_form_end([ [ undef, $text{'save'} ],
			     [ 'delete', $text{'delete'} ] ]);
	}
else {
	print &ui_form_end([ [ undef, $text{'save'} ] ]);
	}

&ui_print_footer("list_records.cgi?dom=$in{'dom'}", $text{'records_return'},
	         &domain_footer_link($d),
		 "", $text{'index_return'});

# ttl_field(name, value)
# Returns a field for entering a TTL
sub ttl_field
{
my ($name, $ttl) = @_;
my $ttl_units;
if ($ttl =~ /^(\d+)([a-z])$/i) {
	$ttl = $1;
	$ttl_units = lc($2);
	}
else {
	$ttl_units = "s";
	}
return &ui_textbox($name, $ttl, 5)." ".
	&ui_select($name."_units", $ttl_units || "s",
		   [ [ "s", $bind8::text{'seconds'} ],
		     [ "m", $bind8::text{'minutes'} ],
		     [ "h", $bind8::text{'hours'} ],
		     [ "d", $bind8::text{'days'} ],
		     [ "w", $bind8::text{'weeks'} ] ], 1, 0, 1);
}
