--[[
Copyright (c) 2012-2015 Kaarle Ritvanen
See LICENSE file for license details
--]]

local M = require('aconf.model')


local RecordString = M.object.class(M.String)

function RecordString:decode(context, value)
   return (value:match('^"(.*)"$') or value):gsub('%\\(.)', '%1')
end

function RecordString:encode(context, value)
   return value:match('^[A-Za-z%d%.%-:]*$') or '"'..value:gsub(
      '(["\\])', '\\%1'
   )..'"'
end


local Record = M.new()
Record.class = RecordString{
   required=true, default='IN', visible=false, editable=true
}
Record.ttl = RecordString{ui_name='Time-to-live'}
Record.type = M.String{
   required=true,
   choice={'A', 'AAAA', 'CNAME', 'MX', 'NAPTR', 'NS', 'PTR', 'SOA', 'SRV'}
}
Record.rdata = RecordString{
   condition={type={'A', 'AAAA', 'CNAME', 'NS', 'PTR'}},
   required=true,
   ui_name='Resource data'
}
Record.priority = M.Integer{condition={type={'MX', 'SRV'}}, required=true}

Record.exchange = RecordString{condition={type='MX'}, required=true}

Record.order = M.Integer{condition={type='NAPTR'}, required=true}
Record.preference = M.Integer{condition={type='NAPTR'}, required=true}
Record.flags = RecordString{condition={type='NAPTR'}, required=true}
Record.service = RecordString{condition={type='NAPTR'}, required=true}
Record.regexp = RecordString{
   condition={type='NAPTR'}, required=true, ui_name='Regular expression'
}
Record.replacement = RecordString{condition={type='NAPTR'}, required=true}

Record.mname = RecordString{
   condition={type='SOA'}, required=true, ui_name='Primary server'
}
Record.rname = RecordString{
   condition={type='SOA'}, required=true, ui_name='Responsible'
}
Record.serial = RecordString{condition={type='SOA'}, required=true}
Record.refresh = RecordString{condition={type='SOA'}, required=true}
Record.retry = RecordString{condition={type='SOA'}, required=true}
Record.expiry = RecordString{condition={type='SOA'}, required=true}
Record.minimum = RecordString{condition={type='SOA'}, required=true}

Record.weight = M.Integer{condition={type='SRV'}, required=true}
Record.port = M.net.Port{condition={type='SRV'}, required=true}
Record.target = RecordString{condition={type='SRV'}, required=true}


local Zone = M.new()
Zone.origin = M.String{addr='$ORIGIN'}
Zone.ttl = M.String{addr='$TTL', ui_name='Time-to-live'}
Zone.records = M.Collection{
   key=M.String{pattern='[^$].*'},
   type=M.List{
      type=M.Model{model=Record, addr='*/*'},
      be_mode='enumerate',
      ui_member='Record'
   },
   addr='.',
   ui_member=''
}


M.register(
   'dns-zone',
   M.Collection{
      type=Zone, addr='/augeas/var/bind/pri', ui_name='DNS zones', ui_member=''
   }
)

M.permission.defaults('/dns-zone')
