You have to fill the UPPER parts with your network and password.
This is for anope irc services and untested - I hope you get the idea anyway.
Also note that you must not open multiple connections to that network. The script else will likely ghost in circles laugh

Code:
; connect
on *:connect: {
  if ($network == YOURNETWORK) { 
    ; current nickname is not main nickname: try to take main nickname
    if ($me != $mnick) { nick $mnick }
    ; set "marker"
    set -eu10 %autoghost 1
  }
}

; raw "nick already in use"
raw 433:*: {
  if ($network == YOURNETWORK) {
    ; if nick in use is your main nickname and "marker" found
    if ($2 == $mnick) && (%autoghost == 1) {
      ; try to ghost that nickname
      msg nickserv ghost $2 YOURPASSWORD
      ; update "marker"
      set -eu10 %autoghost 2
    }
  }
}

; notice from nickserv
on *:notice:*:?: { 
  if ($network == YOURNETWORK) && ($nick == nickserv) {
    ; notice is "ghost killed" and updated "marker" found
    if ($1- == ghost with your nick has been killed.) && (%autoghost == 2) {
      ; try to take main nickname
      nick $mnick
      ; remove marker
      unset %autoghost
    }

    ; ##### this part is to "autoidentify" (optional) #####
    ; notice is "identify for nickname" and you're on your main nickname: identify for nick
    elseif (*identify*pass* iswm $1-) && ($me == $mnick) { msg nickserv identify YOURPASSWORD }
    ; ##### (end if optional autoidentify part) #####

  }
}