/*---------------------------------------------------------------------------*
  Project:  CTR_TRIAL
  File:     sys_WriteSerialNumber.cpp

  Copyright (C)2010 Nintendo Co., Ltd.  All rights reserved.

  These coded instructions, statements, and computer programs contain
  proprietary information of Nintendo of America Inc. and/or Nintendo
  Company Ltd., and are protected by Federal copyright law.  They may
  not be disclosed to third parties or copied or duplicated in any form,
  in whole or in part, without the prior written consent of Nintendo.

 *---------------------------------------------------------------------------*/
#include "sys_WriteSerialNumber.h"
#include "sys_GetRegionCode.h"
#include <nn/cfg/CTR/cfg_ApiInit.h>

using namespace nn::cfg::CTR::detail;
using namespace nn::cfg::CTR::init;

extern bool uji::sys::WriteSerialNumber( const char* serialNumber )
{
    nn::Result nnResult;

    // ダミー署名データ
    u8 sigDummy[ 256+1 ];
    std::memset( sigDummy, 0x00, sizeof( sigDummy ));
    std::memcpy (sigDummy, "AAAAAAAAAA111111111122222222223333333333444444444455555555556666666666777777777788888888889999999999AAAAAAAAAA111111111122222222223333333333444444444455555555556666666666777777777788888888889999999999AAAAAAAAAA1111111111222222222233333333334444444444555555", 256 );

    nn::cfg::CTR::detail::SecureInfoBody secInfo;

    // SecureInfoBodyを取得
    nnResult = GetSecureInfoBody( &secInfo );
    if ( nnResult.IsFailure())
    {
        NN_LOG("GetSecureInfo failed.\n");
        nn::dbg::PrintResult( nnResult );
        return false;
    }

    // SecureInfoBodyの値を更新する
    std::memcpy( secInfo.serialNo, serialNumber, CFG_SECURE_INFO_SERIAL_NO_LEN ); //シリアルNO
    secInfo.region = SerialNumberToRegionCode( serialNumber[1] );

    // SecureInfoBodyのDumpを行う
    u8* u8DispPtr = NULL;
    u8DispPtr =  reinterpret_cast<u8*>( &secInfo );
    NN_LOG(" SecureInfoBody:\n  ");
    for( int i = 0; i < 17; i++ )
    {
        if ( i == 16 ) NN_LOG("\n  ");

        NN_LOG("%02X ", *u8DispPtr );
        u8DispPtr++;
    }
    NN_LOG("\n");

    //SecureInfoにデータを設定する
    nnResult = SetSecureInfo( &secInfo, sigDummy );
    if ( nnResult.IsFailure())
    {
        NN_LOG("SetSecureInfo failed.\n");
        nn::dbg::PrintResult( nnResult );
        return false;
    }

    //データをflushする
    nnResult = FlushSecureInfo();
    if ( nnResult.IsFailure())
    {
        NN_LOG("FlushSecureInfo failed.\n");
        nn::dbg::PrintResult( nnResult );
        return false;
    }
    
    return true;
}

