#  Собираем deb-пакеты
Difrex (mira, 14) → All  –  08:48:29 2016-02-10

Продолжаю адаптировать для ii статьи из корпоративного бложика.
Побудило на написание этой статьи, то что нет нормальной статьи где просто объясняется сборка деб-пакета без премудростей.
Конечно, существует книга от меинтейнеров Debian GNU/Linux и она хороша! Но въехать сразу не получиться.
А ведь на начальном этапе нам скорее всего захочется опакетить свой простой срипт не углубляясь в дебри debian/rules, и.т.д.

Если возникнут вопросы, то спрашивайте. На текущий момент я меинтейню около 40 пакетов + отвечаю за управление репозиториями.

Статья начинается тут.
--
* Сборка deb-пакета

*Важно*

Устанавливаем переменные окружения
====
cat >>~/.bashrc <<EOF
export DEBEMAIL="your.email.address@example.org"
export DEBFULLNAME="Firstname Lastname"
EOF

. ~/.bashrc
====

* Генерация ключа GPG

Ставим GnuPG(скорее всего уже стоит):
====
apt-get install gnupg
====

Генерируем ключ:
====
gpg --gen-key
gpg (GnuPG) 1.4.12; Copyright (C) 2012 Free Software Foundation, Inc.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Please select what kind of key you want:
(1) RSA and RSA (default)
(2) DSA and Elgamal
(3) DSA (sign only)
(4) RSA (sign only)
Your selection? 1
RSA keys may be between 1024 and 4096 bits long.
What keysize do you want? (2048)
Requested keysize is 2048 bits
Please specify how long the key should be valid.
0 = key does not expire
<n> = key expires in n days
<n>w = key expires in n weeks
<n>m = key expires in n months
<n>y = key expires in n years
Key is valid for? (0) 2y
Key expires at Fri Feb 24 06:23:31 2017 UTC
Is this correct? (y/N) y

You need a user ID to identify your key; the software constructs the user ID
from the Real Name, Comment and Email Address in this form:
"Heinrich Heine (Der Dichter) <heinrichh@duesseldorf.de>"

Real name: Vasya Pupkin
Email address: vasya@pupkin.org
Comment: Primary key for sign
You selected this USER-ID:
"Vasya Pupkin (Primary key for sign) <vasya@pupkin.org>"

Change (N)ame, (C)omment, (E)mail or (O)kay/(Q)uit? O
You need a Passphrase to protect your secret key.

You don't want a passphrase - this is probably a *bad* idea!
I will do it anyway. You can change your passphrase at any time,
using this program with the option "--edit-key".

We need to generate a lot of random bytes. It is a good idea to perform
some other action (type on the keyboard, move the mouse, utilize the
disks) during the prime generation; this gives the random number
generator a better chance to gain enough entropy.
...+++++
.........+++++
We need to generate a lot of random bytes. It is a good idea to perform
some other action (type on the keyboard, move the mouse, utilize the
disks) during the prime generation; this gives the random number
generator a better chance to gain enough entropy.
.+++++
.+++++
gpg: /home/vasya/.gnupg/trustdb.gpg: trustdb created
gpg: key B8FB4F1B marked as ultimately trusted
public and secret key created and signed.

gpg: checking the trustdb
gpg: 3 marginal(s) needed, 1 complete(s) needed, PGP trust model
gpg: depth: 0 valid: 1 signed: 0 trust: 0-, 0q, 0n, 0m, 0f, 1u
gpg: next trustdb check due at 2017-02-24
pub 2048R/B8FB4F1B 2015-02-25 [expires: 2017-02-24]
Key fingerprint = 7ADC D709 8FCD 1BCE 78BB 8B2C 9CE1 ABB8 B8FB 4F1B
uid Vasya Pupkin (Primary key for sign) <vasya@pupkin.org>
sub 2048R/FC16A5D6 2015-02-25 [expires: 2017-02-24]
====

Отвечаем на простые вопросы, вводим свое настоящее имя, почту и пароль. Затем gpg попросит вас совершать какие-нибудь действия для лучшей энтропии.
Экспортируем открытый ключ:
====
$ gpg --list-key
/home/vasya/.gnupg/pubring.gpg
------------------------
pub 2048R/B8FB4F1B 2015-02-25 [expires: 2017-02-24]
uid Vasya Pupkin (Primary key for sign) <vasya@pupkin.org>
sub 2048R/FC16A5D6 2015-02-25 [expires: 2017-02-24]
$ gpg -a --export 'Vasya Pupkin (Primary key for sign) <vasya@pupkin.org>' > vasya.pub
====

Отправляем получившийся файлик администратору вашего репозитория.

Смысл в том, что проверка подлинности сборщика происходит при помощи сверки подписи пакета при загрузке его в репозиторий.

Устанавливаем необходимые пакеты для сборки:
====
apt-get install debhelper dh-make dh-make-perl devscripts
====

* Hello world!

Создадим структуру
====
$ mkdir hello-world-0.0
$ cd hello-world-0.0
$ dh_make -n -s -e vasya@pupkin.org -c gpl3 -y
Maintainer name : vasya
Email-Address : vasya@pupkin.org
Date : Wed, 25 Feb 2015 06:48:44 +0000
Package Name : hello-world
Version : 0.0
License : gpl3
Type of Package : Single
Currently there is no top level Makefile. This may require additional tuning.
Done. Please edit the files in the debian/ subdirectory now. You should also
check that the hello-world Makefiles install into $DESTDIR and not in / .
====
Не обращаем внимания на то, что dh_make ругается на отсутсвие мейкфайла -- он нам и не нужен.

Смотрим, что нам нагенерили скрипты:
====
.
|-- debian
| |-- README
| |-- README.Debian
| |-- README.source
| |-- changelog
| |-- compat
| |-- control
| |-- copyright
| |-- docs
| |-- emacsen-install.ex
| |-- emacsen-remove.ex
| |-- emacsen-startup.ex
| |-- hello-world.cron.d.ex
| |-- hello-world.default.ex
| |-- hello-world.doc-base.EX
| |-- init.d.ex
| |-- manpage.1.ex
| |-- manpage.sgml.ex
| |-- manpage.xml.ex
| |-- menu.ex
| |-- postinst.ex
| |-- postrm.ex
| |-- preinst.ex
| |-- prerm.ex
| |-- rules
| |-- source
| | `-- format
| `-- watch.ex
`-- hello_world.sh
====
Из всего того, что находится в ./debian/ мы оставим только:
====
.
|-- debian
| |-- changelog
| |-- compat
| |-- control
| |-- copyright
| `-- rules
`-- hello_world.sh
====

Редактируем ./debian/changelog и приводим его к следующему виду:
====
$ vim ./debian/changelog
hello-world (0.1) updates; urgency=low

* Initial Release.

-- Vasya <vasya@pupkin.org> Wed, 25 Feb 2015 06:48:44 +0000
:wq
====

В дальнейшем для бампа версии рекомендую использовать dch -i

Создадим файл ./debian/install

* Про исходники с ./configure make make install

Для облегчения заполнения файла рекомендую воспользоваться данным методом
====
$ ./configure --prefix=<YOUR_PREFIX>
$ make && make install

$ cd <YOUR_PREFIX>
$ for i in `find -type f | sed 's/^..//'`; do echo $(basename "$i") "usr/$(dirname $i)"; done > <SOURCE_DIR>/debian/install
====

На примере пакета smcroute файл install будет таким
====
mcsender usr/bin
smcroute usr/bin
mcsender.8 usr/share/man/man8
smcroute.8 usr/share/man/man8
smcroute.conf usr/share/doc/smcroute
ChangeLog usr/share/doc/smcroute
smcroute.init usr/share/doc/smcroute
AUTHORS usr/share/doc/smcroute
COPYING usr/share/doc/smcroute
TODO usr/share/doc/smcroute
README usr/share/doc/smcroute

Обратите внимание, что переде путем не стоит первого '/' -- это правильно.
====

* Продолжаем про Hello World!

./debian/control, главный файл. Но в таком пакете, как у нас там нечего редактировать практически:
====
Source: hello-world
Section: dev
Priority: extra
Maintainer: Vasya Pupkin <vasya@pupkin.org>
Build-Depends: debhelper (>= 8.0.0)
Standards-Version: 3.9.3
Homepage: <insert the upstream URL, if relevant>
#Vcs-Git: git://git.debian.org/collab-maint/hello-world.git
#Vcs-Browser: http://git.debian.org/?p=collab-maint/hello-world.git;a=summary

Package: hello-world
Architecture: any
Depends: ${shlibs:Depends}, ${misc:Depends}
Description: My first debian package
====

* debuild

Собираем пакет:
====
$ debuild -k'Vasya Pupkin (Primary key for sign) <vasya@pupkin.org>'
# Вывод пропущен
signfile hello-world_0.0.dsc Vasya Pupkin (Primary key for sign) <vasya@pupkin.org>

signfile hello-world_0.0_amd64.changes Vasya Pupkin (Primary key for sign) <vasya@pupkin.org>

Successfully signed dsc and changes files
====

Через опцию -k можно указать какой использовать ключ, если он у вас, как и у меня, не один.

Мы получили в итоге такие вот файлы:
====
hello-world-0.0
hello-world_0.0.dsc
hello-world_0.0.tar.gz
hello-world_0.0_amd64.build
hello-world_0.0_amd64.changes
hello-world_0.0_amd64.deb
====

* debrelease/dupload/dput

Настало время загрузить пакет в репозиторий. Конфиг для debrelease/dupload:
====
cat > ~/.dupload.conf << EOF
package config;

$preupload{'changes'} = '/usr/share/dupload/gpg-check %1';

$cfg{'master'} = {
fqdn => "example.com",
method => "scpb",
incoming => "/srv/repo/packages/mini-dinstall/incoming/",
# files pass on to dinstall on master which sends emails itself
dinstall_runs => 1,
};

1;
EOF
====

Теперь можно залить пакет. Находясь в каталоге с исходниками выполним:
====
$ debrelease --to master
====

Конфиг dput:
====
~/$ cat > .dput.cf << EOF
[master]
fqdn = example.com
method = scp
login = *
incoming = /srv/repo/packages/mini-dinstall/incoming
EOF
====

Загрузка пакета. Переходим в каталог выше:
====
$ cd ../
$ dput master hello-world_0.0_amd64.changes
====

*Мне больше нравится использовать dput, т.к. у debrelease/dupload сносит крышу от ssh на нестандартном порту.*

(ɔ) Difrex <difrex.punk@gmail.com> 2015-2016 and
w1r0x <vv1r0x@gmail.com> 2015

Лицензия Creative Commons
Это произведение доступно по лицензии Creative Commons «Attribution-ShareAlike» («Атрибуция — На тех же условиях») 4.0 Всемирная.