#!/usr/bin/ruby -w
#
# Copyright (c) 2006 Meraki Networks, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, subject to the conditions
# listed in the Meraki.LICENSE file. These conditions include: you must
# preserve this copyright notice, and you cannot mention the copyright
# holders in advertising related to the Software without their permission.
# The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. This
# notice is a summary of the Meraki.LICENSE file; the license in that file is
# legally binding.
#

dev = "/dev/mtdblock1"

panicdata = `dd if=#{dev} bs=64k skip=1 2>/dev/null`
panicstrings = `dd if=#{dev} bs=64k skip=1 2>/dev/null | strings`

reason = "unknown"

if IO.read("/MERAKI_ARCH").chomp == "mips" && panicstrings.length > 1000
  reason = "kernel panic"

  puts "a kernel panic occurred on last boot, copying to /tmp/LOG_panic"
  panicstrings.tr!('<>','()')
  file = open("/tmp/LOG_panic", "a")
  file.puts(panicstrings)
  file.close
  
  puts "clearing the old kernel panic log"
  flash = open("|dd of=#{dev} bs=64k seek=1 count=1", "w")
  flash << (("" << 0xff) * (64*1024))
  flash.close
end
if File.exists?("/storage/meraki-watchdog.rebootstatus")
  puts "the watchdog caused us to reboot"
  reason = "watchdog"
  system("mv /storage/meraki-watchdog.rebootstatus /tmp/LOG_watchdog")
end

puts "we rebooted for reason: #{reason}"

logGeneral = open("/tmp/LOG_general", "a")
logGeneral.puts("REBOOT: #{reason}")
logGeneral.close
