Skip to content

Instantly share code, notes, and snippets.

@oxc
Created December 5, 2013 14:46
Show Gist options
  • Save oxc/7806225 to your computer and use it in GitHub Desktop.
Save oxc/7806225 to your computer and use it in GitHub Desktop.
VIM script for updating serials in bind zone files Put this in your .vimrc to bind the command to F4: map <F4> :call UpdateDNSSerialZone()<CR>
function! s:ParseSerial()
"Search for a line that start with a year and contains the word Serial
let numberOfLine = search('\(19\|20\)\d\d\(0[1-9]\|1[012]\)\(0[1-9]\|[12][0-9]\|3[01]\)\d\d.*[Ss]erial.*')
if numberOfLine == 0
echo "No bind serial found ! so not updating the file"
return { 'lineNo': 0 }
else
"Get the line contents
let line = getline(numberOfLine)
"Extract the serial number
let serialStart = match(line,'\(19\|20\)\d\d\(0[1-9]\|1[012]\)\(0[1-9]\|[12][0-9]\|3[01]\)')
let serialEnd = match(line, '\D', serialStart+1)
let prefix = strpart(line, 0, serialStart)
let serial = strpart(line, serialStart, serialEnd-serialStart)
let suffix = strpart(line, serialEnd)
return { 'lineNo': numberOfLine, 'prefix': prefix, 'serial': serial, 'suffix': suffix}
endif
endfunction
function! s:UpdateSerial(parsed)
" Initialisation des variables
let serial=0
let serialUpdated=0
let parsed = a:parsed
if parsed.lineNo != 0
" Create a new server number for today
let serialUpdated=strftime("%Y%m%d")."00"
" If the found serial date matches the one from today then we have to
" increment
if parsed.serial =~ "^.*".strftime("%Y%m%d").".*"
let serialUpdated=parsed.serial+1
endif
" Build a new line with the updated serial
let line = parsed.prefix . serialUpdated . parsed.suffix
" Write the line back to the file
call setline(parsed.lineNo, line)
set modified
echo "Old serial = \"". parsed.serial ."\" updated serial to = \"".serialUpdated."\""
endif
endfunction
function! s:CheckSerial(currentSerial)
let l:newSerial = s:ParseSerial()
if l:newSerial.lineNo == 0
echohl WarningMsg
echo "This looks like a zone file, but I couldn't find a serial number"
echohl None
return
endif
if a:currentSerial.lineNo == 0
return
endif
if l:newSerial.serial == a:currentSerial.serial
echohl WarningMsg
echo "WARNING: The zone's serial number did not change since this file was opened."
echohl None
endif
endfunction
" This function is used to update the serial in the SOA from a bind file
function! UpdateDNSSerialZone()
call s:UpdateSerial(s:ParseSerial())
endfunction
"set verbose=9
augroup SerialUpdate
autocmd! BufRead db.* ks|let b:currentSerial = s:ParseSerial()|'s
autocmd! BufWritePost db.* ks|call s:CheckSerial(b:currentSerial)|'s
"autocmd! BufUnload db.* ks|call s:CheckSerial(b:currentSerial)|'s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment