「gem install kindai」出来ず、rubygem アップデートとSSLの証明書エラーに困る。（解決済み）

MacOSX 10.9
ruby 2.1.10p492　ー＞ruby 2.2.5p319
$ gem -v
2.4.5.1


国会図書館デジタルライブラリーダウンローダーをインストールしたい。
（国会図書館デジタルライブラリーの旧名は近代デジタルライブラリー）
GitHub - hitode909/kindairb: 近代デジタルライブラリーダウンローダ
https://github.com/hitode909/kindairb



#１．gem install kindaiでエラーが起こり、SSLのエラーも対処できない。

```
$ gem install kindai
ERROR:  Could not find a valid gem 'kindai' (>= 0), here is why:
          Unable to download data from https://rubygems.org/ - SSL_connect returned=1 errno=0 state=error: certificate verify failed (https://api.rubygems.org/latest_specs.4.8.gz)

$ gem install kindai --source https://github.com/hitode909/kindairb
ERROR:  Could not find a valid gem 'kindai' (>= 0), here is why:
          Unable to download data from https://rubygems.org/ - SSL_connect returned=1 errno=0 state=error: certificate verify failed (https://api.rubygems.org/latest_specs.4.8.gz)
          Unable to download data from https://github.com/hitode909/kindairb/ - bad response Not Found 404 (https://github.com/hitode909/kindairb/latest_specs.4.8.gz)
```


#２．gem をアップデートしてもSSLエラー

SSL Certificate Update - RubyGems Guides
http://guides.rubygems.org/ssl-certificate-update/#installing-using-update-packages

gem をアップデートする必要があるらしい。
普通にアップデートしてもSSLエラー

```
$sudo gem update --system
ERROR:  While executing gem ... (Gem::RemoteFetcher::FetchError)
    SSL_connect returned=1 errno=0 state=error
```

#３．rubygemインストールに成功

SSL Certificate Update - RubyGems Guides
http://guides.rubygems.org/ssl-certificate-update/#installing-using-update-packages
によれば、以下のとおりらしい。

[C:\>gem install --local C:\rubygems-update-2.6.11.gem]

解凍したディレクトリには、rubygems-update-2.6.11.gemは存在しないので

```
$ sudo ruby ./setup.rb
```
を実行。gem2.6.11はインストールされる。

```
$ gem -v
2.6.11
```

#４．証明書のインストールしてもSSLエラー

gem2.6.11インストールしても、何故かSSLエラー状況が変わらない。

参考
Windowsでgem installするとSSLエラーが出る場合の解決策 - Qiita
http://qiita.com/shimoju/items/394818b4989b94680aaf

SSL Certificate Update - RubyGems Guides
http://guides.rubygems.org/ssl-certificate-update/#installing-using-update-packages
上記URLの「Manual solution to SSL issue」を参考に証明書のインストール。

[homedir]/.rbenv/versions/2.1.10/lib/ruby/2.1.0/rubygems/ssl_certs/
に、AddTrustExternalCARoot-2048.pemをコピー。

.pemをコピーしても、何故かSSLエラー状況が変わらない。

#５．SSLのエラーがまだ続く。

ログに「expired at 2014-01-28T12:00:00Z」とあるので、未だに古い証明書を参照している模様。
ログにファイル名もないので、どのpemを参照してエラーになっているか分からない。
rubygem公式ではSSLの証明書ファイルである.pemを更新しろ、と書かれているが
厳密な手順ではなく、間違っているのではないだろうか？
今の所、SSLを差し替える方法はお手上げ。

```
$ gem install kindai
ERROR:  SSL verification error at depth 2: certificate has expired (10)
ERROR:  Certificate /C=BE/O=GlobalSign nv-sa/OU=Root CA/CN=GlobalSign Root CA expired at 2014-01-28T12:00:00Z
ERROR:  SSL verification error at depth 2: certificate has expired (10)
ERROR:  Certificate /C=BE/O=GlobalSign nv-sa/OU=Root CA/CN=GlobalSign Root CA expired at 2014-01-28T12:00:00Z
ERROR:  SSL verification error at depth 2: certificate has expired (10)
ERROR:  Certificate /C=BE/O=GlobalSign nv-sa/OU=Root CA/CN=GlobalSign Root CA expired at 2014-01-28T12:00:00Z
ERROR:  Could not find a valid gem 'kindai' (>= 0), here is why:
          Unable to download data from https://rubygems.org/ - SSL_connect returned=1 errno=0 state=error: certificate verify failed (https://api.rubygems.org/specs.4.8.gz)
ERROR:  SSL verification error at depth 2: certificate has expired (10)
ERROR:  Certificate /C=BE/O=GlobalSign nv-sa/OU=Root CA/CN=GlobalSign Root CA expired at 2014-01-28T12:00:00Z
```

#６．pemファイルを検索、grep

```
$ find / -name \*.pem -print0 | xargs -0 ggrep --color 2014
/Users/xxxxxxxx/source/curl-7.47.1/tests/stunnel.pem:            Not Before: Feb 22 15:38:48 2014 GMT
```

一つだけ見つかるが、お手上げ。

ruby 2.1.10p492をアンインストールして、最近のrubyをインストールするしかないか？

#７．rubyのバージョンを上げるとSSLは解決

rbenvでrubyのバージョンを上げた。

```
$ ruby -v
ruby 2.2.5p319 (2016-04-26 revision 54774) [x86_64-darwin13]

$ gem -v
2.4.5.1
```

するとSSLの問題は解決した。
わけもわからず、ruby 2.2.5p319にしてしまった。
ruby2.2.5p319が2.2.5の最終版であることぐらいしか認識がない。


SSLの問題が無くなったが、今度はkindaiインスト時のRMagickインストールエラー。

```
$ gem install kindai
Building native extensions.  This could take a while...
ERROR:  Error installing kindai:
	ERROR: Failed to build gem native extension.

/Users/xxxxxxxxx/.rbenv/versions/2.2.5/bin/ruby -r ./siteconf20170318-14435-1gqkher.rb extconf.rb
checking for clang... yes
checking for Magick-config... no
checking for pkg-config... yes
checking for outdated ImageMagick version (<= 6.4.9)... no
checking for presence of MagickWand API (ImageMagick version >= 6.9.0)... no
checking for Ruby version >= 1.8.5... yes
checking for stdint.h... yes
checking for sys/types.h... yes
checking for wand/MagickWand.h... no

Can't install RMagick 2.16.0. Can't find MagickWand.h.
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.
```

#８．gem install rmagick でインストール失敗

次の問題が発生した。(笑)

gem install rmagick でインストール失敗 - Qiita
http://qiita.com/tajihiro/items/3f10c59f19fcd0a9e660

homebrewでインストールすると失敗するらしい。
imagemagickインスト時の　./configureのオプションの問題だろうか？


参考：homebrewバージョン７のオプションはこんな感じらしい
（==> ./configure --disable-osx-universal-binary --prefix=/usr/local/Cellar/imagemagick/7.0.5-2 --disable-silent-rules --enable-shared --enable-static --with-modules --disable-opencl --disable-openmp --without-webp --without-openjp2 --without-gslib --with-gs-font-dir=/usr/local/share/ghostscript/fonts --without-fftw --without-pango --without-x --with-freetype=yes）


#９．「imagemagickのバージョンを７ではなく６にする」とgem install rmagick でインストール可能に

bundle install "rmagick" でインストールができない - Qiita
http://qiita.com/sho012b/items/362abe993248c686fcf4#_reference-4aa90991b151d5e21d84

imagemagickのバージョンを７ではなく６にする必要があるらしい。

```
$ brew uninstall imagemagick

$ brew install imagemagick@6

$ brew link --force imagemagick@6
Linking /usr/local/Cellar/imagemagick@6/6.9.8-0... 75 symlinks created

$ convert --version
Version: ImageMagick 6.9.8-0 Q16 x86_64 2017-03-18 http://www.imagemagick.org
Copyright: © 1999-2017 ImageMagick Studio LLC
License: http://www.imagemagick.org/script/license.php
Features: Cipher DPC Modules 
Delegates (built-in): bzlib freetype jng jpeg ltdl lzma png tiff xml zlib

$ gem install rmagick
Building native extensions.  This could take a while...
Successfully installed rmagick-2.16.0
Parsing documentation for rmagick-2.16.0
Installing ri documentation for rmagick-2.16.0
Done installing documentation for rmagick after 7 seconds
1 gem installed
```

#１０．gem install kindaiのインストールエラーまでたどり着いた。

また、次の問題が発生した。(笑)

```
$ gem install kindai
Fetching: mini_portile2-2.1.0.gem (100%)
Successfully installed mini_portile2-2.1.0
Fetching: nokogiri-1.7.0.1.gem (100%)
Building native extensions.  This could take a while...
ERROR:  Error installing kindai:
	ERROR: Failed to build gem native extension.

    /Users/xxxxxxxx/.rbenv/versions/2.2.5/bin/ruby -r ./siteconf20170318-49170-q2uhd4.rb extconf.rb
checking if the C compiler accepts ... yes
checking if the C compiler accepts -Wno-error=unused-command-line-argument-hard-error-in-future... yes
Building nokogiri using packaged libraries.
Using mini_portile version 2.1.0
checking for iconv.h... yes
checking for gzdopen() in -lz... yes
checking for iconv... yes
************************************************************************
IMPORTANT NOTICE:

Building Nokogiri with a packaged version of libxml2-2.9.4.

Team Nokogiri will keep on doing their best to provide security
updates in a timely manner, but if this is a concern for you and want
to use the system library instead; abort this installation process and
reinstall nokogiri as follows:

    gem install nokogiri -- --use-system-libraries
        [--with-xml2-config=/path/to/xml2-config]
        [--with-xslt-config=/path/to/xslt-config]

If you are using Bundler, tell it to use the option:

    bundle config build.nokogiri --use-system-libraries
    bundle install

Note, however, that nokogiri is not fully compatible with arbitrary
versions of libxml2 provided by OS/package vendors.
************************************************************************
Extracting libxml2-2.9.4.tar.gz into tmp/x86_64-apple-darwin13.4.0/ports/libxml2/2.9.4... OK
Running 'configure' for libxml2 2.9.4... OK
Running 'compile' for libxml2 2.9.4... ERROR, review '/Users/xxxxxxxx/.rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/nokogiri-1.7.0.1/ext/nokogiri/tmp/x86_64-apple-darwin13.4.0/ports/libxml2/2.9.4/compile.log' to see what happened. Last lines are:
========================================================================
    unsigned short* in = (unsigned short*) inb;
                         ^~~~~~~~~~~~~~~~~~~~~
encoding.c:815:27: warning: cast from 'unsigned char *' to 'unsigned short *' increases required alignment from 1 to 2 [-Wcast-align]
    unsigned short* out = (unsigned short*) outb;
                          ^~~~~~~~~~~~~~~~~~~~~~
4 warnings generated.
  CC       error.lo
  CC       parserInternals.lo
  CC       parser.lo
  CC       tree.lo
  CC       hash.lo
  CC       list.lo
  CC       xmlIO.lo
xmlIO.c:1450:52: error: use of undeclared identifier 'LZMA_OK'
    ret =  (__libxml2_xzclose((xzFile) context) == LZMA_OK ) ? 0 : -1;
                                                   ^
1 error generated.
make[2]: *** [xmlIO.lo] Error 1
make[1]: *** [all-recursive] Error 1
make: *** [all] Error 2
========================================================================
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.

Provided configuration options:
	--with-opt-dir
	--without-opt-dir
	--with-opt-include
	--without-opt-include=${opt-dir}/include
	--with-opt-lib
	--without-opt-lib=${opt-dir}/lib
	--with-make-prog
	--without-make-prog
	--srcdir=.
	--curdir
	--ruby=/Users/xxxxxxxx/.rbenv/versions/2.2.5/bin/$(RUBY_BASE_NAME)
	--help
	--clean
	--use-system-libraries
	--enable-static
	--disable-static
	--with-zlib-dir
	--without-zlib-dir
	--with-zlib-include
	--without-zlib-include=${zlib-dir}/include
	--with-zlib-lib
	--without-zlib-lib=${zlib-dir}/lib
	--enable-cross-build
	--disable-cross-build
/Users/xxxxxxxx/.rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/mini_portile2-2.1.0/lib/mini_portile2/mini_portile.rb:366:in `block in execute': Failed to complete compile task (RuntimeError)
	from /Users/xxxxxxxx/.rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/mini_portile2-2.1.0/lib/mini_portile2/mini_portile.rb:337:in `chdir'
	from /Users/xxxxxxxx/.rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/mini_portile2-2.1.0/lib/mini_portile2/mini_portile.rb:337:in `execute'
	from /Users/xxxxxxxx/.rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/mini_portile2-2.1.0/lib/mini_portile2/mini_portile.rb:111:in `compile'
	from /Users/xxxxxxxx/.rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/mini_portile2-2.1.0/lib/mini_portile2/mini_portile.rb:150:in `cook'
	from extconf.rb:364:in `block (2 levels) in process_recipe'
	from extconf.rb:257:in `block in chdir_for_build'
	from extconf.rb:256:in `chdir'
	from extconf.rb:256:in `chdir_for_build'
	from extconf.rb:363:in `block in process_recipe'
	from extconf.rb:262:in `tap'
	from extconf.rb:262:in `process_recipe'
	from extconf.rb:547:in `<main>'

extconf failed, exit code 1

Gem files will remain installed in /Users/xxxxxxxx/.rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/nokogiri-1.7.0.1 for inspection.
Results logged to /Users/xxxxxxxx/.rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/extensions/x86_64-darwin-13/2.2.0-static/nokogiri-1.7.0.1/gem_make.out
$ 
```
行うべき対処方法が書かれているにもかかわらず、これくらい長いエラーログだと
事例がない場合、自分だけでは１１番の対処が難しい。

上から順に推測できるのは次の通り。
推測
１．Nokogiriインストール結果がエラーかワーニングか謎。
２．Running 'compile' for libxml2 2.9.4... ERRORなのでlibxml2に着目すべき？
３．xmlIO.c:1450:52: error: use of undeclared identifier 'LZMA_OK'
xmlIO.cエラーが根本原因なら全くのお手上げ。



#１１．「nokogiri」のインストエラーに対処。

kindaiのインストールエラーではなく「nokogiri」のインストエラー。

macOS Sierra での gem install nokogiri でエラー - Qiita
http://qiita.com/riocampos/items/43b55ba06e6c3ec01b82

--------'170320追記--------
Mac OS X Mavericksで”gem i nokogiri”失敗の解決方法 - Qiita
http://qiita.com/t_732_twit/items/a7956a170b1694f7ffc2
--------'170320追記--------

```
$ brew install libxml2
Updating Homebrew...
==> Auto-updated Homebrew!
Updated 1 tap (homebrew/core).
==> Updated Formulae
cargo-completion  ipfs              nss               tomcat            tomcat@7          varnish
groovy            lzo               rgbds             tomcat@6          tomcat@8.0

==> Using the sandbox
==> Downloading http://xmlsoft.org/sources/libxml2-2.9.4.tar.gz
######################################################################## 100.0%
==> Downloading https://mirrors.ocf.berkeley.edu/debian/pool/main/libx/libxml2/libxml2_2.9.4+dfsg1-2.2.deb
######################################################################## 100.0%
==> Patching
==> Applying patches/0003-Fix-NULL-pointer-deref-in-XPointer-range-to.patch
patching file result/XPath/xptr/viderror
patching file test/XPath/xptr/viderror
patching file xpath.c
==> Applying patches/0004-Fix-comparison-with-root-node-in-xmlXPathCmpNodes.patch
patching file xpath.c
==> Applying patches/0005-Fix-XPointer-paths-beginning-with-range-to.patch
patching file xpath.c
patching file xpointer.c
==> Applying patches/0006-Disallow-namespace-nodes-in-XPointer-ranges.patch
patching file xpointer.c
==> Applying patches/0007-Fix-more-NULL-pointer-derefs-in-xpointer.c.patch
patching file xpointer.c
==> Applying patches/0008-Fix-attribute-decoding-during-XML-schema-validation.patch
patching file xmlschemas.c
==> ./configure --prefix=/usr/local/Cellar/libxml2/2.9.4_2 --without-python --without-lzma
==> make
==> make install
==> Caveats
This formula is keg-only, which means it was not symlinked into /usr/local.

macOS already provides this software and installing another version in
parallel can cause all kinds of trouble.

If you need to have this software first in your PATH run:
  echo 'export PATH="/usr/local/opt/libxml2/bin:$PATH"' >> ~/.bash_profile

For compilers to find this software you may need to set:
    LDFLAGS:  -L/usr/local/opt/libxml2/lib
    CPPFLAGS: -I/usr/local/opt/libxml2/include
For pkg-config to find this software you may need to set:
    PKG_CONFIG_PATH: /usr/local/opt/libxml2/lib/pkgconfig

==> Summary
🍺  /usr/local/Cellar/libxml2/2.9.4_2: 277 files, 10MB, built in 1 minute 9 seconds
```

ログのとおりに　.bash_profile　を編集する。
「brew link --force libxml2」
「gem install nokogiri -- --use-system-libraries」

```
$ brew link --force libxml2
Linking /usr/local/Cellar/libxml2/2.9.4_2... 17 symlinks created
$ gem install nokogiri -- --use-system-libraries
Building native extensions with: '--use-system-libraries'
This could take a while...
Successfully installed nokogiri-1.7.0.1
Parsing documentation for nokogiri-1.7.0.1
Installing ri documentation for nokogiri-1.7.0.1
Done installing documentation for nokogiri after 9 seconds
1 gem installed
```




#１２．gem install kindaiに成功した。

```
$ gem install kindai
Fetching: kindai-2.8.0.gem (100%)
Successfully installed kindai-2.8.0
Parsing documentation for kindai-2.8.0
Installing ri documentation for kindai-2.8.0
Done installing documentation for kindai after 0 seconds
1 gem installed

$ which kindai.rb
/Users/xxxxxxxxx/.rbenv/shims/kindai.rb
```