local skynet = require "skynet"
require "skynet.manager"
local logger = require "logger"
local stringify = require "stringify"
local usercenter = skynet.localname(".usercenter")
local logind = skynet.localname(".loginserver")
local redisdriver = require "skynet.db.redis"
local namecenter = skynet.localname(".namecenter")
local md5 = require "md5"

local cjson = require "cjson"

local authz = {acc = "yytx", pwd = "lee@YY-Games.520"}
-- Generate request data
local content = {acc = authz.acc, pwd = authz.pwd, sign = false}
content.sign = string.sub(md5.sumhexa(content.acc .. content.pwd), 9, 24)

local whitelist = {
  ["192.168.1.23"] = true,
  ["192.168.1.127"] = true,
  ["192.168.1.41"] = true,
  ["222.212.88.4"] = true,
}

--[[
    byname = zlf        -- 玩家的名字
]]

-- example:
--[[
    type = 1/2      1: 获取当前时间 2:设置时间 3:指定格式修改时间
    time = utc      目标时间
    http://192.168.1.51:9001/set_time?user=yytx&pwd=lee@YY-Games.520&arg={"type":1,"time":0}
    http://192.168.1.51:9001/set_time?user=yytx&pwd=lee@YY-Games.520&arg={"type":2,"time":1531822162}
    http://192.168.1.51:9001/set_time?user=yytx&pwd=lee@YY-Games.520&arg={"type":3,"time":"2018-7-17 17:44:50"}
]]
local function modify_time(args, ipaddr, header)
  logger.trace("处理来自主机 %s 的 服务器时间设置请求", ipaddr)
  if not whitelist[ipaddr] then
    --return { "403 - Forbidden" }
    -- return cjson.encode({errno = 403, host = header.host, info = "不信任ip"})
  end


  -- 验证gm账号
  local code = string.sub(args.code, 1, 16)
  if code ~= content.sign then
    return cjson.encode({state = 403, msg = "账号或密码错误"})
  end

  local par = cjson.decode(args.arg)
  if par.type == 1 then                     -- 获取系统时间
    -- 直接返回即可
  elseif par.type == 2 then                 -- 设置系统时间
    -- 检查时间
    if par.time <= os.time() then
        return cjson.encode({state = 403,msg = "errno less than now time"})
    end
    -- 转换时间格式
    local format = os.date("%Y-%m-%d %X", par.time)
    local key = string.format("sudo date -s '%s'", format)
    logger.trace(" === %s", key)
    local ret,ret2 = os.execute(key)
    logger.trace("ret = %s, ret2 = %s", ret, ret2)
    if not ret then
        -- return cjson.encode({errno = 403, host = header.host, info = "errno args.time"})
        return cjson.encode({state = 403, state = "errno abnormal"})
    end
  elseif par.type == 3 then                 -- 设置系统时间
    logger.trace(" === --- %s", par.time)
    local key = string.format("sudo date -s '%s'", par.time)
    logger.trace(" === %s", key)
    local ret,ret2 = os.execute(key)
    logger.trace("ret = %s, ret2 = %s", ret, ret2)
    if not ret then
        return cjson.encode({state = 403, msg = "errno args.time"})
    end
  else
    return cjson.encode({state = 403, msg = "errno ars.type"})
  end
  return cjson.encode({state = 0, msg = "set succeed",type = par.type, time = os.time(),format = os.date("%Y-%m-%d %X", os.time())})
end

return modify_time